How to Get Last Inserted ID in Laravel?

10-Apr-2023

.

Admin

Hello Artisan,

This is a short guide on get last inserted id in laravel. This example will help you get last inserted id from table in laravel. We will look at an example of how to get last inserted id in laravel. you'll learn laravel get last inserted id 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...

#Laravel

#Laravel 6