How to return last added id in laravel?

by muriel.schmidt , in category: PHP CMS , 8 months ago

How to return last added id in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 8 months ago

@muriel.schmidt 

You can return the last added ID in Laravel by using the insertGetId() method on the Eloquent model. This method inserts a record into the database and returns the ID of the newly inserted record. Here is an example of how you can do this:

1
2
3
4
5
6
7
8
use AppModelsUser;

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

$lastInsertedId = $user->id;


In this example, we are creating a new User model, setting its attributes, and then saving it to the database. The id property of the $user object will now contain the ID of the newly inserted record, which can be assigned to the $lastInsertedId variable.


Alternatively, you can also use the create() method along with the id property to get the last inserted ID:

1
2
3
4
5
6
$user = User::create([
    'name' => 'John Doe',
    'email' => '[email protected]',
]);

$lastInsertedId = $user->id;


Both methods will return the last inserted ID in Laravel.