Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

349
Vistas
Laravel UpdateOrCreate To Be Different values on Create on Update

Is there something like UpdateOrCreate I can use to have different values on create and on update. Meaning if it’s updating i don’t want it to change a certain column but i want it to insert the first time. eg

$person = ['name'=> 'John', 'age' => 6, 'joined' => '2017-01-01'];

If John exists update age. If it doesn’t insert age and joined;

People::updateOrCreate(
            ['name' => $person['name']],
            ['age' => $person['age'], 'joined' => $person['joined']]
        )

will update joined every time and i don't wanna change it.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can use updateOrNew which doesn't persist it to the database and then check if it is not already in the database you can change the property you want to change.

$record = People::updateOrNew(
        ['name' => $person['name']],
        ['age' => $person['age']]
);

if(!$record->exists()) {
    $record->joined = $person['joined'];
}

$record->save();

But if you are only trying to get the record if it exists and create it if it doesn't, use firstOrCreate() instead. That won't affect existing records, only return them, and it will create the record if it doesn't exist.

over 4 years ago · Santiago Trujillo Denunciar

0

There is no any other option else you can try following:

 $person = People::where('name', $name)->first();
  
        if (!is_null($person)) {
            $person->update([
                'age' => $age
            ]);
        }else{
            $person = People::create([
                'name' => $name,
                'age' => $age,
                'joined' => date('Y-m-d')
            ]);
        }  
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda