In Laravel Eloquent, you can use the
latest()
method along with the first()
or firstOrFail()
method to retrieve the last record from a database table based on the default timestamp column (usually created_at
). Here’s an example:
// Using latest() and first()
$lastRecord = YourModel::latest()->first();
// Using latest() and firstOrFail()
$lastRecordOrFail = YourModel::latest()->firstOrFail();
In the above examples, replace
YourModel
with the actual name of your Eloquent model. The latest()
method orders the query results by the specified column in descending order, which means the newest records will be at the top. The first()
method then retrieves the first record from the result set, effectively giving you the last record based on the default timestamp column.
If you use firstOrFail(), it will retrieve the first record or throw an exception if no records are found. This can be useful if you want to handle the case where there might not be any records in a more controlled way.
You can also specify a custom column to order by if your timestamps are stored in a different column. For example:
$lastRecord = YourModel::latest('custom_timestamp_column')->first();
Replace custom_timestamp_column
with the actual column name you want to use for ordering.
Remember to replace YourModel
with the actual name of your Eloquent model.