10

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?

Blackbam
  • 14,898
  • 22
  • 85
  • 134
  • 1
    Possible duplicate of [Laravel, get last insert id using Eloquent](https://stackoverflow.com/questions/21084833/laravel-get-last-insert-id-using-eloquent) – chiliNUT Oct 25 '17 at 15:33

2 Answers2

22

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

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

$id = $object->id;
Alexey Mezenin
  • 148,626
  • 22
  • 267
  • 261
-3

Query for the last one

$lastRecord = MyModel::last();

Or

$lastRecord = MyModel::orderBy('id', 'DESC')->first();
Lloople
  • 1,757
  • 1
  • 15
  • 30
  • 3
    This wouldn't always get you the right record, say you had a table of 40 rows, the updateOrCreate method updates id 20, neither of the above would return the one updated. The above would only work if it created a new record. – JLeggatt Oct 25 '17 at 15:40
  • Yes, you're right, you'll have to use `updated_at` if you're using timestamps. Otherwise there's no other way (unless you save the id like Alexey said. I thought the question was about different requests. – Lloople Feb 02 '18 at 08:17