how to get last inserted id in laravel 6?

Admin   Laravel   415  2021-03-17 08:40:11

In this example, i will give you simple example of how to get last inserted id in laravel 6. you can simply get laravel 6 get last inserted record id with example.

,when you create database,you many a time use primary key column using the AUTO_INCREMENT attribute that means when you insert new record into the table then value of primary key column will be auto-increment with unique integer.

Whenever you perform an INSERT or UPDATE on database table with an AUTO_INCREMENT column then you get the last insert id of last insert or update query.

In PHP, you use mysqli_insert_id to get last inserted record id.

In laravel, when you go with DB query builder then you can use insertGetId() that will insert a record and then return last inserted record id.

Example 1:


public function getLastInsertedId()


$id = DB::table('users')->insertGetId(

['email' => '[email protected]', 'name' => 'Mehul']




Example 2:


public function getLastInsertedId()


$user = User::create(['name'=>'Mehul' , 'email'=>'[email protected]']);



It will help you...