How to Get the Last Inserted Id Using Laravel 6.0

Four Simple Ways to get last Inserted Id in Laravel 6.0

Here in this article, I'm going to share with you how to get last inserted ID in laravel with 4 simple method. 
You want to get last inserted ID in laravel application. In following i have discussed about 4 different way to get last inserted ID in laravel. You can use any of the following way to get last ID of inserted record in laravel application.

If you have experience with PHP and Laravel then you almost know the require to get last inserted Id. So, You need to get last insert Id then you can use save(), create() and insertGetId() method in laravel application. In this post, i am going to describe Four way to get last inserted Id in laravel application.

So, in this post i am going to show you four example for getting last insert Id in Laravel Application:
Those are -
  1. insertGetId() method
  2. lastInsertId() method
  3. create() method and
  4. save() method.
Now, I am going to describe the above four method one by one.
  • insertGetId() method - There is the following code sample
public function getLastInsertedId() { 
 $a = ['name' => 'Amit Sarker', 'email'=>'antu123@gmail.com']; 
 $b = User::create($a); 
 return $b->id; 
}
  • lastInsertId() method - There is the following code sample
public function getLastInsertedId() { 
 DB::getPdo()->lastInsertId(); 
}
  • create() method - There is the following code sample
public function getLastInsertedId() {
 $id = DB::table('users_table') 
 ->insertGetId( 
  ['name' => 'Amit Sarker', 'email'=>'antu123@gmail.com'] 
 ); 
return $id; 
}
  • save() method - There is the following code sample
public function getLastInsertedId(){ 
 $user_data =new User(); 
 $user_data->name = "Amit Sarker"; 
 $user_data->email = "antu123@gmail.com"; 
 $user_data->save(); 
 return $user->id; 
}
Here, In this video, I'm going to apply one method. You can follow my video to get last inserted Id.
Thank you.


EmoticonEmoticon