How to get latest record based on one column in laravel?

by mallory_cormier , in category: PHP Frameworks , 5 months ago

How to get latest record based on one column in laravel?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by raven_corwin , 2 months ago

@mallory_cormier 

To get the latest record based on one column in Laravel, you can use the latest() method provided by Eloquent ORM along with orderBy() method.


Here is an example of how you can achieve this:

1
2
// Get the latest record based on the created_at column
$latestRecord = YourModel::orderBy('created_at', 'desc')->first();


In this example, replace YourModel with the name of your Eloquent model and created_at with the column based on which you want to get the latest record. The orderBy('created_at', 'desc') method sorts the records in descending order based on the created_at column and the first() method retrieves the first record from the sorted result set, which will be the latest record.