11

2 Ways To Get Latest Record By Date With Laravel

 3 years ago
source link: https://www.codewall.co.uk/2-ways-to-get-latest-record-by-date-with-laravel/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

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

last record from table eloquent laravel

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 –

Output

latest record in laravel table method 2

If we wanted to convert this to an array, it can be done with a one-liner of code as I’ve demonstrated in an article about converting objects to arrays here.

And boom, that is it, two methods to get the latest record from any data table with a DateTime column. Hope this helps!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK