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?


You can actually do this within the query.

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

This will return all results with the proper order.


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


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.

链接地址: http://www.djcxy.com/p/67470.html

上一篇: 在Android上处理SQLite表和游标

下一篇: Laravel雄辩:所有订单结果()