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.