Search code examples
phplaraveleloquentupsertlaravel-5.5

Eloquent / Laravel: How to get last insert/update ID/instance of updateOrCreate()?


The title is mostly self-explanatory. Eloquent has a method called

updateOrCreate()

documented here: https://laravel.com/docs/5.5/eloquent#other-creation-methods

In some cases this is really useful. However after doing updateOrCreate() I need either the updated/created object or its primary key or its id.

Of course I could do MyModel::where(...)->first() and give all those data again but this is clumsy and may be some expensive request.

However updateOrCreate() only returns true or false.

Any ideas?


Solution

  • The method will return ID of created or updated object, so just do this:

    $object = Model::updateOrCreate(['name' => 'John'], ['age' => 25]);
    
    $id = $object->id;