How to get last insert id in Eloquent ORM laravel
In Laravel, you can use the save
method provided by Eloquent to insert a new record and retrieve the last insert ID. After calling the save
method, you can access the id
property of the model to get the last insert ID. Here's an example:
<?php
$user = new User();
$user->name = 'John Doe';
$user->email = '[email protected]';
$user->save();
$lastInsertId = $user->id;
Watch a video course
Learn object oriented PHP
Alternatively you can also use create
method of Eloquent which will save the record and return the instance of saved model, then you can get the last insert ID using id
property
<?php
$user = User::create(['name' => 'John Doe', 'email' => '[email protected]']);
$lastInsertId = $user->id;
You can also use the insertGetId
method on the model's query builder to insert a new record and retrieve the last insert ID in a single step.
<?php
$lastInsertId = User::insertGetId(['name' => 'John Doe', 'email' => '[email protected]']);
Please note that these method are available only for those tables which have auto increment id column.