In this post, I would like to show the different ways to get last inserted ID from the database table when working with Laravel PHP Framework. In the core PHP, we will get last inserted ID with
PDO::lastInsertId() methods, but in Laravel framework you don’t need have to use those methods.
In the Laravel framework, we can interact with the database using query builder and Eloquent ORM, Here in this post I will show you getting last inserted ID in both approaches.
Laravel’s Query builder
While working with Query builder you can use
insertGetId() method, that will insert a record and then return last inserted record id as a response.
$userID = DB::table('users')->insertGetId(
['email' => '[email protected]', 'name' => 'Arjun A']
Laravel’s Eloquent ORM
While working with Eloquent ORM, we can use
create() method to insert data into the database table and it will return the inserted model instance, form that instance object we can grab the last inserted ID
$user = User::create(['email' => '[email protected]', 'name' => 'Arjun A']);