Posted by Arjun on Sunday 27th May 2018

How to get last inserted id in Laravel

How to Last Inserted ID Laravel Laravel 5 Laravel 5.1 Laravel 5.2 laravel 5.3 Laravel 5.4 Laravel 5.5 Laravel 5.6 Laravel 5.7

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 mysqli_insert_id() or 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']
 print_r($userID );

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']);