Reputation: 19366
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?
Upvotes: 11
Views: 18750
Reputation: 13
$insertid = DB::table('temp_registration_master')->insertGetId($master_detail);
Upvotes: 1
Reputation: 163748
The method will return ID of created or updated object, so just do this:
$object = Model::updateOrCreate(['name' => 'John'], ['age' => 25]);
$id = $object->id;
Upvotes: 28
Reputation: 1844
Query for the last one
$lastRecord = MyModel::last();
Or
$lastRecord = MyModel::orderBy('id', 'DESC')->first();
Upvotes: -4