Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

346
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!