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?
all() is a static method on the Eloquent\Model . All it does is create a new query object and call get() on it. With all() , you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters).
By default, Laravel Eloquent models return queries that are ordered by the id column of the model table. With this package, you can set default order by in your Eloquent model so you don't have to call the orderBy Eloquent builder.
To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database. You'll now change the code in your routes/web.
$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 .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With