I'm stuck on a simple task. I just need to order results coming from this call

$results = Project::all();

Where Project is a model. I've tried this

$results = Project::all()->orderBy("name");

But it didn't work. Which is the better way to obtain all data from a table and get them ordered?

shareimprove this question
 
正确答案 
up vote180down voteaccepted

You can actually do this within the query.

$results = Project::orderBy('name')->get();

This will return all results with the proper order.

shareimprove this answer
 

You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

Ascending Order

$results = Project::all()->sortBy("name");

Descending Order

$results = Project::all()->sortByDesc("name");

Check out the documentation about Collections for more details.

https://laravel.com/docs/5.1/collections

shareimprove this answer
 
   
Exactly what I was looking for. Would extensive use of this have any downsides compared to using orderByat the query level? – Giedrius Apr 18 at 12:33
   
\@foreach ($posts->sortByDesc('created_at') as $post) \@include('posts.post') \@endforeach – sdexp Apr 23 at 20:53

In addition, just to buttress the former answers, it could be sorted as well either in descending desc or ascending asc orders by adding either as the second parameter.

$results = Project::orderBy('created_at', 'desc')->get();

Hope this helps.

shareimprove this answer
 
   
Thanks! It is solved to me! :) – Francis Rodrigues Jun 14 at 18:20

2017 update


Laravel 5.4 added orderByDesc() methods to query builder:

$results = Project::orderByDesc('name')->get();
shareimprove this answer
 

Check out the sortBy method for Eloquent: http://laravel.com/docs/eloquent

shareimprove this answer
 

来自  https://stackoverflow.com/questions/17429427/laravel-eloquent-ordering-results-of-all