How to get last inserted id in Laravel 8

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' => 'HackTheStuff',
    ]);

    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' => 'Jitesh Meniya',
    ]);

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

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

Was this article helpful?

0 out of 0 person found this article helpful.

Leave a comment

Or

No Comment