Share this:

Hello dev, Today we are going to learn to Get the Last Inserted Id Using Laravel Eloquent. 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 blog 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 = new User;
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->save();

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.

Also Read : How to Set, Get, and Delete Cookies in Laravel 10

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;

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

Step 3: 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' => 'Jane Smith',
    'email' => 'janesmith@example.com',
]);

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.

Also Read: Laravel Add a new column to existing table in a migration

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.

Share this:

Categorized in: