Get Last Insert ID in Laravel Eloquent ORM: A Step-by-Step Guide

  1. Introduction
  2. Step 1: Create a Model
  3. Step 2: Insert Data into the Table
  4. Step 3: Get the Last Insert ID
  5. Conclusion


When working with Laravel's Eloquent ORM, getting the last insert ID is a common task. In this step-by-step guide, we'll walk through the process of retrieving the last insert ID using Laravel's Eloquent ORM.

Step 1: Create a Model

The first step is to create a model that will represent the table you want to insert data into. In this example, let's say we have a "users" table, and we want to create a new user and get the last insert ID.

To create the "users" model, run the following command:

php artisan make:model User

This will create a new "User" model in the "app" directory.

Step 2: Insert Data into the Table

Once you have your model, you can use it to insert data into the "users" table. Here's an example:

$user = new User;
$user->name = 'John Doe';
$user->email = '';

This will create a new user record in the "users" table.

Step 3: Get the Last Insert ID

To get the last insert ID, you can simply call the "id" property on the model after you save it. Here's an example:

$lastInsertID = $user->id;

This will retrieve the ID of the last inserted record in the "users" table.


Retrieving the last insert ID in Laravel's Eloquent ORM is a simple process. By following these steps, you can easily retrieve the last insert ID for any table in your Laravel application.

Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information