How to Get the Last Insert ID with Laravel Eloquent
When you create a new record using Eloquent, Laravel automatically populates the model's ID property with the value of the newly inserted record's primary key. Here's a straightforward example:$user = new User;
$user->name = "Tom";
$user->phone = "+154483480";
$user->save();
After the save method, use something like
$last_Insert_Id = $user->id;
$user->name = "Tom";
$user->phone = "+154483480";
$user->save();
After the save method, use something like
$last_Insert_Id = $user->id;
In this snippet, $user->save() stores the new record in the database. Eloquent then automatically updates the $user object's id property with the ID of the newly inserted record.
Why is this feature important?
Obtaining the last inserted ID is crucial in many scenarios, such as redirecting users to a newly created resource, creating relationships between new and existing records, or logging activities. Laravel's Eloquent ORM makes this process seamless and efficient, enhancing the developer's productivity.Using Custom Query Builder
We can get the last insert ID with the help of the query builder as well.Here is a below snippet example.
$last_id = DB::table('products')->insertGetId(['id' => 22]);