Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

laravel 5.2 - Model::all() order by

Tags:

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?

like image 316
datavoredan Avatar asked Feb 07 '16 05:02

datavoredan


People also ask

What does all () do in Laravel?

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).

What is default order by in Laravel?

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.

How do I use orderBy in Laravel eloquent?

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.


3 Answers

$posts = Post::orderBy('created_at', 'desc')->get();

You can use the orderBy method. Replace the column name with the one you want.

like image 134
Jilson Thomas Avatar answered Sep 24 '22 14:09

Jilson Thomas


You can now use sortBy or sortByDesc:

$posts = Post::all()->sortBy('created_at');
like image 27
Nicolas Perraut Avatar answered Sep 24 '22 14:09

Nicolas Perraut


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 .

like image 2
conrad10781 Avatar answered Sep 21 '22 14:09

conrad10781