How to get last inserted id in Laravel 8

  5164 views   6 months ago Laravel

When you insert any record in database, you may want to insert other tables for the current inserted recorded id. So when you insert record, you will need to know what is the id of inserted record.

In this article, I will give you example of how you can get last inserted record's id in laravel 8. You can get laravel 8 get last inserted record id with following example in controller.

If you are using query builder, you may use use insertGetId() method which insert the record and returns id of record.

/**
 * create new instance of the class
 *
 * @return void
 */
public function create()
{
    $id = \DB::table('users')->insertGetId([
        'email' => '[email protected]',
        'name' => 'Harsukh Makwana',
    ]);

    dd($id); // 5
}

And here is example with eloquent query. create() method returns the last inserted record object. So you can access object property as below:

use App\Models\User;

/**
 * create new instance of the class
 *
 * @return void
 */
public function create()
{
    $user = User::create([
        'email' => '[email protected]',
        'name' => 'Harsukh Makwana',
    ]);

    dd($user->id); // 5
}

I hope it will help you. Thank you for reading article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]