Laravel 5.5 get last inserted record Id

Today, We are learning how we get the last inserted record Id on Laravel. Many times we need the last inserted record Id for the further operation. Laravel provides many ways to fire record insert query. Let’s see the different way to get the last inserted record Id using Laravel method.

If you insert record using DB::table the command, there are two ways to get the last inserted record Id. The first of all, we can get the last inserted  Id using insertGetId Method.

$insertId = DB::table('thecodingstuff')->insertGetId([
   'title' => 'the coding stuff',
   'description' => 'the coding stuff',
   'price' => '$10' 
]);

dd($insertId);

The second way we can get the last inserted Id using lastInsertId method like below.

DB::table('thecodingstuff')->insertGetId([
   'title' => 'the coding stuff',
   'description' => 'the coding stuff',
   'price' => '$10' 
]);
$id = DB::getPdo()->lastInsertId();;
dd($id);

Now, let’s see how we can get the last inserted record Id using Laravel model. When insert query fire using Laravel model how we can get the last inserted Id.

First of all, we discuss the create method of Laravel model eloquent. We can easily insert records using Laravel eloquent model. Let’s how we can create the new record and get the last inserted record Id.

$data = ThecodingStuff::create([
       'title' => 'the coding stuff',
       'description' => 'the coding stuff',
       'price' => '$10' 
    ]);
dd($data->id);

We discuss the save method of Laravel model eloquent. When we insert record using save method then you can get the last inserted Id like.

$data = new ThecodingStuff;
$data->title = 'the coding stuff';
$data->description = 'the coding stuff';
$data->price = '$10';
$data->save();
dd($data->id);

So we discuss the different insert method of Laravel and how to get the last inserted record Id for every method. So it’s too easy to get the last inserted record Id using Laravel.

If you face any issue after using above code write the comment below.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s