PASSWORD RESET

Your destination for complete Tech news

How to get the last inserted id in Laravel eloquent?

316 0
< 1 min read

To get the last inserted ID in Laravel Eloquent, you can use the id property of the model instance after saving it to the database.

For example, if you have a User model and you want to get the ID of the last inserted user, you can do the following:

$user = new User;
$user->name = 'John';
$user->email = '[email protected]';
$user->save();

$lastInsertedId = $user->id;

Alternatively, you can use the latest method on the model to fetch the last inserted record:

$lastInsertedUser = User::latest()->first();
$lastInsertedId = $lastInsertedUser->id;

Keep in mind that the latest method will order the results by the created_at column in descending order, so make sure that your model has a created_at column and that it is properly populated.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.