How to get last inserted id in Laravel?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this blog i will show you how to get last inserted data id in laravel. We know that It’s very common need to get last insert id in development field, if we are working on laravel framework and we must want to fetch last created id, here i mean max id, then we can do this easily . We know in laravel provide method to get last inserted id.

When we are working with DB::table() then we need to use insertGetId() for insert data into database. We know that this function always return us inserted record id(primary key). We know this is a very simple way to get id, in following example when we can see and understand more:

Example:
public function getLastInsertedIdDB()
{
	$id = DB::table('items')->insertGetId(['name'=>'hello']);
	print_r($id);
}

But, when we are insert record by using laravel Model then it is pretty simple to get it without using any special function like insertGetId(), now in following example we can see and how to use i create method.

Read Also : How to find day from specific date in PHP?

Example:

public function getLastInsertedIdModel()
{
	$create = Item::create(['name'=>'hello']);
	print_r($create->id);
}

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →