how to get last inserted id in laravel?

Today, We want to share with you get last inserted id in laravel.In this post we will show you laravel last insert id we have needed some it last inserted ID in laravel application, hear for how to get last inserted ID in laravel with 4 simple example we will give you demo and example for implement.In this post, we will learn about
get lastInsertId
with an example.

Laravel Get Last Inserted ID With Example

we have find Four diffrent way to get last inserted ID. you can use it and get last ID of inserted record in php web application.

How to get last record from MySQL table in Laravel
How to get last record from MySQL table in Laravel

1) Using insertGetId() function

using insertGetId()
We can get last inserted ID using insertGetId() in laravel for example

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

dd($id);

2) Using lastInsertId() function

using lastInsertId()
We can also get last inserted ID using lastInsertId(). We need PDO object to run this function for example

Read Also:  die in php

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

3) Using create() function.

Yes, you can also get last ID using of create() function with Model. this methods is return last inssert recod’s object as well as you can get using this object last inserted ID.

for simple example

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

4) Using save() function.

We can also get last inserted ID using save() function. if you use save() function for insert data then you can get last inserted id such that

$users = new User;
$users->name = 'Rohit';
$users->save();
dd($users->id);

I hope you get an idea about last insert id.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.