Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Seif5's avatar

view the most recent date

Hello ,

How i can select the most recent date with laravel ?

0 likes
15 replies
bestmomo's avatar

hello

Just with orderBy, for example :

Post::orderBy('created_at', 'desc')->first();
michaeldyrynda's avatar

You could also use the latest() method in Laravel 5.

Post::latest()->get();
1 like
bestmomo's avatar

@deringer I didn't know this short syntax ! It adds an orderBy to the query, so I also found the oldest that gets the oldest one.

2 likes
Seif5's avatar

@deringer thank you for the answer , but i want to select Closest to today's date ??

michaeldyrynda's avatar

@SeifBh the latest() method is just a shortcut version of what was posted above i.e. an order by created_at desc.

Also, you never know what you'll find digging through the API docs @bestmomo ;)

Seif5's avatar

@bestmomo , @deringer yes i know , but only the administrator car change the date (the date will be insert manually by the adminstrator of the website) , that's mean i have a column date in my database !! and i want to display the closest date in my database !

michaeldyrynda's avatar

If you have future dates, I suppose you might do something like

// First record after now
Model::where('created_at', '>=', $yourDate)->orderBy('created_at', 'asc')->first();

// First record before now
Model::where('created_at', '<=', $yourDate)->orderBy('created_at', 'desc')->first();

And that will give you the first record in the database after now. Without context in your app, it's hard to say if this will achieve what you're after though.

3 likes
bestmomo's avatar

I must say I dont really understand this date story ^^

2 likes
Seif5's avatar

@bestmomo lol , i build a football website , and i want to display the closest to today's date... Note : i insert this date manually with phpmyadmin what solution you propose

pmall's avatar

Man try to learn by yourself. We wont build your website instead of you.

Seif5's avatar

@pmall thank you for the advice , but this website for people like me .

JarekTkaczyk's avatar

@SeifBh @deringer @bestmomo This is how you get timestamp closest to now:

// mysql with second precision
Model::orderByRaw(' abs( timestampdiff(second, current_timestamp, created_at)) asc ')->first();

// postgres with second precision
Model::orderByRaw(' abs( extract(epoch from now()) - extract(epoch from created_at) asc ')->first();

Please or to participate in this conversation.