Laravel 5.5 - Get Last Inserted ID With Example

In this article, we will share with you how to get last inserted id of the inserted record in laravel. here we can get this type of solution help of 4 different way. many time we need it how to get last inserted id of the inserted records.

1) Using insertGetId() method

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

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

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

    'name' => 'TestName'
$id = DB::getPdo()->lastInsertId();;

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 inserted ID. for example.

$data = User::create(['name'=>'first']);

4) Using save() method.

You can also get last inserted 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';

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