I get the full collection of a Model with the following:
$posts = Post::all();
However I want this is reverse chronological order.
What is the best way to get this collection in the desired order?
I get the full collection of a Model with the following:
$posts = Post::all();
However I want this is reverse chronological order.
What is the best way to get this collection in the desired order?
$posts = Post::orderBy('created_at', 'desc')->get();
You can use the orderBy method. Replace the column name with the one you want.
You can now use sortBy
or sortByDesc
:
$posts = Post::all()->sortBy('created_at');
As many may be moving to newer versions of Laravel, you can use ::latest() starting in 5.3 - https://laravel.com/docs/5.5/queries#ordering-grouping-limit-and-offset .