How to get last insert id in Eloquent ORM laravel
In Laravel, you can use the save method provided by Eloquent to insert a new record and retrieve the last insert ID.
In Laravel, you can use the save method provided by Eloquent to insert a new record and retrieve the last insert ID. After calling the save method, you can access the id property of the model to get the last insert ID. Here's an example:
Example of using the save method provided by Eloquent to insert a new record and retrieve the last insert ID in Laravel
<?php
$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->save();
$lastInsertId = $user->id;
<div class="alert alert-info flex not-prose">![]()
<span class="hidden md:block">Watch a video course</span>Learn object oriented PHP</div>
Alternatively you can also use create method of Eloquent which will save the record and return the instance of saved model, then you can get the last insert ID using id property
Example of using create method of Eloquent which will save the record and return the instance of saved model in Laravel
<?php
$user = User::create(['name' => 'John Doe', 'email' => '[email protected]']);
$lastInsertId = $user->id;You can also use the insertGetId method on the model's query builder to insert a new record and retrieve the last insert ID in a single step.
Example of using the insertGetId method on the model's query builder to insert a new record and retrieve the last insert ID in a single step in Laravel
<?php
$lastInsertId = User::insertGetId(['name' => 'John Doe', 'email' => '[email protected]']);Please note that these method are available only for those tables which have auto increment id column.