When doing any CRUD type operation such as creation, obtaining a reference to the element being worked on is crucial and this is done through the post identifier; On creation, depending on the method you use, it may return a bool indicating that the entity was created in the database or it may return the identifier or a reference to the model; but, it is usually necessary to retrieve the last ID inserted into the database after performing an insert operation.
In this post, we will see several ways to obtain a reference to the ID generated in the database.
1. Using the latest Eloquent method to Get the Latest Record
The Laravel ORM, that is, Eloquent, allows you to obtain the last record inserted in a table in a simple way; For this first way, we use the latest() method to sort the records by the ID column in descending order and then call the first() method to obtain the first record (which will be the most recent):
YourModel::latest('id')->first();
2. Using the insertGetId Method
The insertGetId method inserts the record just like the insert or update method and returns the ID upon completing the operation:
$data = [
'f1' => 'V1',
'f2' => 'V2',
];
$id = YourModel::insertGetId($data);
3. Using Eloquent's create Method
Eloquent's create method allows you to insert a new record and recover the model instance and with this, the ID of the record, this is the quintessential scheme to obtain the reference to the ID:
$data = [
'f1' => 'V1',
'f2' => 'V2',
];
$yourModel= YourModel::create($data);
4. Using Eloquent's save method
With the save method we can operate on an existing instance and create the record if it does not exist or update it if it exists (it has the ID established), this method CANNOT be used statically and returns an instance of the model:
$yourModel = new YourModel;
$modelo->f1= 'v1';
$modelo->f2= 'v2';
$yourModel->save();
$yourModel->id;
5. Using insert Method and lastInsertId
If we are using SQL queries directly, we can insert a record and then retrieve its ID using the lastInsertId method.
DB::table('table')->insert([
'f1' => 'v1',
'f2' => 'v2',
]);
$id = DB::getPdo()->lastInsertId();
In this way, and know how you can obtain the reference of the model that you are saving in the database.
I agree to receive announcements of interest about this Blog.
We will see 5 ways to obtain the identifier or instance of the model to be able to obtain the ID in Laravel using Eloquent.
- Andrés Cruz