Laravel Get Last Inserted ID with Example

Laravel get last insert id example; In this tutorial we will show you how to get last inserted ID in laravel application. Many times we need to last inserted id which is saved first in laravel, So here we have find 4 diffrent way to get last inserted ID of eloquent model.

When you create or insert record on database table with an AUTO_INCREMENT column then you get the last insert id of last insert or update query.

1. Using insertGetId() method

For getting the last inserted records in database you can use the insertGetId in laravel just like below.

public function getLastInsertedId()
{
    $lastId = DB::table('users')->insertGetId(
            ['email' => 'xyz@example.com', 'name' => 'Test']
    );

    dd($lastId);
}

2. Get Id after create() method

After saving the data in database you can get the last inserted recrods in laravel something like this:

public function getLastInsertedId()
{
    $user = User::create(['name'=>'Test' , 'email'=>'test@example.com']);

    dd($user->id);
}

3. Using save() method

If you are using save method to inserting records to your database then you can use below example;

public function getLastInsertedId()
{
    $user = new User;
    $user->name = 'Test';
    $user->save();
    dd($user->id);
}

I hope these example help you to getting last insert id in laravel. If you have any other methods please share you answer via comment box we will thankful for you.

Leave a Comment