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.
Here in this article, I'm going to share with you how to get last inserted ID in laravel with 4 simple method.
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 -
- insertGetId() method
- lastInsertId() method
- create() method and
- save() method.
- 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;
}
Thank you.
EmoticonEmoticon