PRASANNA KUMAR K G
PRASANNA KUMAR K G

Reputation: 77

How to find last inserted id, when using laravel firstOrNew new method to inser the data

Am using laravel firstOrNew method to insert the data . when data is not present in the table it will insert the data. after inserting the data am unable to get the last inserted id.

ex:

   $user = User::firstOrNew(['id'=>1]);
   $user->name='prasanna';
   $user->save();
   dd($user->id); //it prints true,  here i need last inserted  id 

Upvotes: 2

Views: 278

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use firstOrCreate instead firstOrNew

firstOrNew is not persisted until save() is not called, so it will not return $user->id here.

firstOrNew returns

return new static($attributes); 

And firstOrCreate returns

return static::create($attributes);

Read the difference

Upvotes: 1

Related Questions