Get the Last Inserted Id Using Laravel Eloquent

Sospeter Mong'are - May 29 '23 - - Dev Community

Introduction:
When working with databases in #Laravel, it is often necessary to retrieve the ID of the last inserted record.

The ID can be useful for various purposes, such as linking related data or performing subsequent operations.

In this post, we will explore how to obtain the last inserted ID using Laravel’s Eloquent ORM, making it easier for you to work with database records in your Laravel applications.
**
Step 1: Save a Record Using Eloquent**
To begin, let’s assume that you have a model representing the table you want to insert data into. In this example, we’ll use a User model that corresponds to a users table.

To save a new record using Eloquent, you can use the following code:

$user = User::create([
        'name' => 'John Doe',
        'email' => 'johndoe@example.com',
]);
Enter fullscreen mode Exit fullscreen mode

Make sure to replace User with the appropriate model class name for your application, and set the desired values for the record you want to insert.

Step 2: Retrieve the Last Inserted ID
After saving the record, you can retrieve the last inserted ID using the id property of the Eloquent model. Here’s an example:

$lastInsertedId = $user->id;
Enter fullscreen mode Exit fullscreen mode

The id property will contain the last inserted ID value, which you can assign to a variable for further use in your application.

Alternative Method – Using the insertGetId Method
Another way to retrieve the last inserted ID is by using the insertGetId method provided by Laravel’s query builder.

This method allows you to insert a record and immediately get the ID of the inserted row. Here’s an example:

$lastInsertedId = DB::table('users')->insertGetId([
    'name' => 'John Doe',
    'email' => 'johndoe@example.com',
]);
Enter fullscreen mode Exit fullscreen mode

In this example, we are inserting a new record into the users table and assigning the last inserted ID to the **$lastInsertedId **variable.

Remember to replace 'users' with the appropriate table name for your application, and adjust the column names and values accordingly.

Conclusion:
Retrieving the last inserted ID is a common requirement when working with databases in Laravel applications. By using Laravel’s Eloquent ORM, you can easily obtain the ID of the last inserted record.

Whether you choose to retrieve the ID from the Eloquent model’s id property or use the insertGetId method of the query builder, both methods provide a straightforward way to access the last inserted ID value.

Incorporate these techniques into your Laravel projects to simplify working with database records and streamline your development process.

Let me know if this helps.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .