How to return last added id in laravel?

by muriel.schmidt , in category: PHP CMS , a year ago

How to return last added id in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , a year 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 = 'john@example.com';
$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' => 'john@example.com',
]);

$lastInsertedId = $user->id;


Both methods will return the last inserted ID in Laravel.

Related Threads:

How to get/return last inserted id in codeigniter?
How to get last inserted id in laravel?
How to return ajax data request by id in octobercms?
How to redirect with id in laravel?
How to get last seven days in laravel?
How to join only last record of the table in laravel?