ChatGPT解决这个技术问题 Extra ChatGPT

Laravel Eloquent: Ordering results of all()

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?


T
Travis B

You can actually do this within the query.

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

This will return all results with the proper order.


And an explanation for get() vs all(): stackoverflow.com/questions/34587457/…
->orderBy() takes two arguments; the second can be 'asc' or 'desc' to sort the results in ascending or descending order. For example, ->orderBy('name', 'desc')
Y
Yannick Y

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


Exactly what I was looking for. Would extensive use of this have any downsides compared to using orderBy at the query level?
\@foreach ($posts->sortByDesc('created_at') as $post) \@include('posts.post') \@endforeach
I'm interested in knowing how this works behind the scenes. It strikes me as though sorting the collection with sortBy() happens inside the Laravel Engine (in PHP), while the orderBy() is done in the database. Surely the database is going to be quicker in almost all conceivable situations, and as your dataset increases so will the disparity in performance. I'd love to hear other people's thoughts on this.
@cartbeforehorse You need to know which method returns what. ::all() probably just calls ->get() under the hood, which, in turn, returns a collection. sortBy() is a method of a collection, so yes it happens on PHP side (as opposed to orderBy() which is called on a query object). It is a bad idea to use ::all() at all, let alone sorting it in PHP. Imagine if ::all() returns a collection with a million of objects. It will take too long to fetch it and even more time to sort it in PHP. Of course, you can use ::all() if you know for sure it will return just a handful of objects (in a collection).
why this one is not the accepted answer? it worked with the all() function.
M
Matthieu

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();

d
doncadavona

DO THIS:

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

Why? Because it's fast! The ordering is done in the database.

DON'T DO THIS:

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

Why? Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.


It would be nice to add explanation why: First approach makes order at the database (query) level which is almost always much more efficient - the best performance. I would say use Model approach always, when you will need the second approach, you will know :)
I think the second way has a better performance. Because first, records are fetched by the default sorting column which is more efficient. and then are sorted in the code.
@AliN11 NO. The first performs faster. It is done in the database level.
S
Sebastien Horin

2017 update

Laravel 5.4 added orderByDesc() methods to query builder:

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

D
DsRaj

While you need result for date as desc

$results = Project::latest('created_at')->get();

H
Hedayatullah Sarwary

In Laravel Eloquent you have to create like the query below it will get all the data from the DB, your query is not correct:

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

You have to use it in this way:

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

By default, your data is in ascending order, but you can use it in the following way:

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

Or in descending order:

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

R
Rob W

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


h
hkcoyant

Note, you can do:

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

This generate a query like:

"SELECT name FROM proyect ORDER BY 'name' ASC"

In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:

$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();

Now is php who order the result.


A
Ardent Coder

You instruction require call to get, because is it bring the records and orderBy the catalog

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

Example:

$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();

In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.


A
Amin.Qarabaqi

One interesting thing is multiple order by:

according to laravel docs:

DB::table('users')
   ->orderBy('priority', 'desc')
   ->orderBy('email', 'asc')
   ->get();

this means laravel will sort result based on priority attribute. when it's done, it will order result with same priority based on email internally.

EDIT:

As @HedayatullahSarwary said, it's recommended to prefer Eloquent over QueryBuilder. off course i didn't encourage using QueryBuilder and we all know that each has own usecases.

Any way so why i wrote an answer with QueryBuilder? As we see in eloquent documents:

You can think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.

BTWS the above code with eloquent should be something like this:

Project::orderBy('priority', 'desc')
->orderBy('email', 'asc')
->get();

You have created your query in Laravel Query Builder, you should use Laravel Eloquent.
@HedayatullahSarwary doesn't make difference. l edited the response. take a look!
h
hackernewbie

Try this:

$categories     =   Category::all()->sortByDesc("created_at");