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
  • 17,496
  • 26
  • 97
  • 150
  • 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

3 Answers3

24

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
  • 158,981
  • 26
  • 290
  • 279
1
$insertid = DB::table('temp_registration_master')->insertGetId($master_detail);
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • 2
    Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan May 05 '23 at 11:58
-3

Query for the last one

$lastRecord = MyModel::last();

Or

$lastRecord = MyModel::orderBy('id', 'DESC')->first();
Lloople
  • 1,827
  • 1
  • 17
  • 31
  • 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