how to get last inserted id in laravel 6?

Laravel 6 , Laravel

Nicesnippets

311

19-09-2019


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' => 'xyz@gmail.com', 'name' => 'Mehul']

);

dd($id);

}

Example 2:

public function getLastInsertedId()

{

$user = User::create(['name'=>'Mehul' , 'email'=>'xyz@gmail.com']);

dd($user->id);

}

It will help you...