loading...

Laravel 5.5 - Get Last Inserted ID With Example

pakainfocom profile image pakainfo ・2 min read

here i have find 4 diffrent methods to get last inserted ID in laravel apps. you can use it and Laravel 5.5 – Get Last Inserted ID With Example get last ID of inserted record in laravel web application.

1) Using insertGetId() method

You can get last inserted ID using insertGetId() in laravel for example

$id = DB::table('users')->insertGetId(
    [ 'name' => '4cgandhi' ]
);

dd($id);

2) Using lastInsertId() method

You can also get last inserted ID using lastInsertId() in laravel. You need PDO object to run this method for example

DB::table('users')->insert([
    'name' => 'TestName'
]);
$id = DB::getPdo()->lastInsertId();;
dd($id);

Bonus

3) Using create() method.

Yes, you can also get last ID using of laravel create() method with laravel Model. this methos is return last inssert recod's object and you can get using this object last insert ID. for example

$data = User::create(['name'=>'4cgandhi']);
dd($data->id);

4) Using save() method.

You can also get last insert ID using laravel save() method. if you use save() method for insert data then you can get last inserted id like that

$data = new User;
$data->name = 'Test';
$data->save();
dd($data->id);

Also Read: Laravel 6.2 Get Last insert ID

We are hope this small web tutorials help everyone. if you known more way to get last insert ID in laravel so please comment bellow. Thanks..

Discussion

pic
Editor guide