Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 221
Blackbam Avatar asked Oct 25 '17 15:10

Blackbam


1 Answers

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

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

$id = $object->id;
like image 73
Alexey Mezenin Avatar answered Nov 06 '22 21:11

Alexey Mezenin