Reputation: 77
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
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