How to get last inserted id in laravel?

Today We are going to learn how we can get the last inserted id in laravel. Laravel provides a very simple function for getting the last inserted record id. Many times we need the last inserted id for the future process like when we are going to store child records at that time we need the last inserted record id.

How to get last inserted id in laravel?

Laravel provides many ways for getting the last inserted id it depends on the which insert method are you used. If you are working with DB::table then you have to use insertGetId() for getting the last inserted id in Laravel. Let's see the example

public function getLastInsertedId()
{
$id = DB::table('product')->insertGetId(['name'=>'item name']);
print_r($id);
}

If you are using Laravel Eloquent for storing records then you can easily get the last inserted id like.

public function getLastInsertedId()
{
$product = Product::create(['name'=>'Item Name']);
print_r($product->id);
}

As per the above example, you can easily get the last inserted records id using the simple Laravel function.

Tags:

Related Posts: