If you have experience with PHP Project developing then you know we almost require to get last id. so if you need to get last insert id then you can get save(), create() and insertGetId() method in laravel 5.6 application. here i will give you three way to get last inserted id or object in laravel 5.6 application.
So in this small article i will give you three example for getting last insert id:
1) save()
2) create()
3) insertGetId()
So you can see following craeteNewUser() method with following three way to get and return last inserted id. you can use any one that is fit for your example. So let's see bellow examples:
Example 1: Using save()
public function craeteNewUser(){
$user_data =new User();
$user_data->name = "Akash Savani";
$user_data->email = "akash@gmail.com";
$user_data->save();
return $user->id;
}
Example 2: Using create()
public function craeteNewUser()
{
$id = DB::table('users')
->insertGetId(
['name' => 'Akash Savani', 'email'=>'akash@gmail.com']
);
return $id;
}
Example 3: Using insertGetId()
public function craeteNewUser()
{
$input = ['name' => 'Akash Savani', 'email'=>'akash@gmail.com'];
$user = User::create($input);
return $user->id;
}
I hope you found your best solution....
Do you like below Tutorials ?
- How to Copy File from One Folder to Another in Laravel?
- How to Move File from One Folder to Another in Laravel?
- Laravel Remove File from Storage Folder Example
- React JS Textbox onchange Event Example
- React JS Textarea onchange Event Example
- React JS Select onchange Event Example
- React JS Radio onchange Event Example
- React JS Checkbox onchange Event Example