How to get the Last Inserted Id Using Laravel Eloquent

Get the Last Inserted Id Using Laravel Eloquent

In this article let’s understand how to get the Last Inserted Id Using Laravel Eloquent.

In Laravel, you can retrieve the last inserted ID using Eloquent after performing an insert operation. Here are a few ways to get the last inserted ID using Laravel’s Eloquent ORM:

Using the insertGetId() method:

$data = [
    'column1' => 'value1',
    'column2' => 'value2',
];

$lastInsertedId = DB::table('table_name')->insertGetId($data);

The insertGetId() method inserts the data into the specified table and returns the last inserted ID.

Using the create() method:

$model = ModelName::create([
    'column1' => 'value1',
    'column2' => 'value2',
]);

$lastInsertedId = $model->id;

The create() method creates a new record in the corresponding Eloquent model’s table and returns the created model instance. You can access the last inserted ID using the id property of the model.

Using the save() method:

$model = new ModelName;
$model->column1 = 'value1';
$model->column2 = 'value2';
$model->save();

$lastInsertedId = $model->id;

The save() method saves the new model instance to the database, and you can retrieve the last inserted ID using the id property.

These are a few examples of how you can retrieve the last inserted ID using Laravel’s Eloquent ORM. Choose the method that suits your application’s requirements and coding style.

Read more articles on Laravel here.