3

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

updateOrNew doesn't seem to be a real method
@jxxe you can use firstOrNew to achieve something similiar
1

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')
            ]);
        }  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.