2 Ways To Get Latest Record By Date With Laravel

Laravel has a couple of ways in which to interrogate the database it’s linked to. In this tutorial, we will explore the four ways that the latest record (by date time) can be pulled out of any specified table. Whether you like to use Eloquent or raw SQL, this article will answer both use-cases.


Method 1

Method one uses Eloquent and utilizes two important operators too pull out the latest record, sortByDesc and take. The sortByDesc method will take a date time stamp as it’s specified column, in this case, the created_at column. After this we instruct a limit of 1 using the take() operator, meaning it will pull out the first record from the collection.


PHP

$lastRecordDate = Product::all()->sortByDesc('created_at')->take(1)->toArray();

dd($lastRecordDate);

// OR

$lastRecordDate = Product::all()->sortByDesc('YOUR_COLUMN_NAME')->take(1)->toArray();

dd($lastRecordDate);

Output



Method 2

The next method utilizes a raw SQL query in pretty much exact fashion to method one. Again we will use sorting and limiting to grab the latest record. In this syntax, sortByDesc is ‘order by’ and take is ‘limit’.

$lastRecordData = DB::select('select * from products order by created_at desc limit 1'); 

dd($lastRecordData);

// OR 

$lastRecordData = DB::select('select * from YOUR_TABLE_NAME order by YOUR_DATE_COLUMN desc limit 1'); 

dd($lastRecordData);

This will give us a similar output of the latest record in the table but in object form –