How to get last inserted id in Laravel 7.x and 6.x?

September 25, 2018 | Category : Laravel 5.7 Laravel 5 Laravel PHP

we can get last insert id in three way to into laravel 5.7 application. laravel provide three model function to get current saved record id as save(), create() and insertGetId().

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.7 project. here i will give you three way to get last inserted id or object in laravel 5.7 project.

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(){

$input = ['name' => 'Akash Savani', 'email'=>'akash@gmail.com'];

$user = User::create($input);

return $user->id;

}

Example 3: Using insertGetId()

public function craeteNewUser(){

$id = DB::table('users')

->insertGetId(

['name' => 'Akash Savani', 'email'=>'akash@gmail.com']

);

return $id;

}

I hope you found your best solution....