How to get last inserted id in Laravel

BOOKC, this time share about How to get last inserted id in Laravel

Today, we will learn How to get the Last Inserted ID in Laravel. In this tutorial, we learn how to get the last inserted ID in Laravel for example. we get the last inserted ID using insertGetId in the Laravel application. so, we have some example ways to get the last inserted ID in Laravel. We use lastInsertId, insertGetId, create, save method used to get the last ID of the inserted record in the Laravel application.

Using lastInsertId() method

We can get the last inserted ID using Laravel default method lastInsertId() with example.

Here are the following methods to get last inserted id

Eloquent

Method 1

$user = new User();
$user->name = "Test";
$user->save();
dd($user->id);

Method 2

$user = User::create(['name' => 'Test']);
dd($user->id);

Query Builder

Method 3

In this method Primary Key must me id. If its other then id for example some_id then this method will throw exception.

$id = DB::table('users')->insertGetId(['name' => 'Test']);
dd($id);

Method 4

This method is usefull if you are using DB Facade and have Custom Primary Key like some_id.

DB::table('users')->insert(['name' => 'Test']);
dd(DB::getPdo()->lastInsertId()); 

I hope this tutorial is very helpful. if have any other known way to get the last inserted ID in Laravel, please leave a comment. Thanks 🙂

Bookc
Admin

Hopefully the information we provide can be useful.

Press ESC to close