How to get the id of current saved model in laravel?

Member

by jerad , in category: PHP Frameworks , 22 days ago

How to get the id of current saved model in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 21 days ago

@jerad 

To get the id of the current saved model in Laravel, you can use the id property of the model object. After saving the model, the id property will be automatically set with the id of the newly saved model.


Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Create a new instance of a model
$model = new YourModel();
$model->name = 'Example';

// Save the model
$model->save();

// Get the id of the saved model
$id = $model->id;

echo $id;


In this example, we first create a new model object and set its attributes. We then call the save() method to save the model to the database. Finally, we can access the id property of the model object to get the id of the saved model.