Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent sortBy - Specify asc or desc

Trying sort my eloquent collection:

$collection->sortBy('field');

There is no information in Laravel 4's docs on how to choose descending or ascending for this sort method.

Is it possible?

like image 301
Lovelock Avatar asked Jun 04 '15 16:06

Lovelock


People also ask

How to fetch data in descending order in Laravel?

If you want to sort data in Descending and Acesending order in Laravel 5.6 it just simple code like this: View::composer('*',function($view){ $view->with('services', Service::latest()->get()); }); Latest function is equal orderBy('created_at', 'DESC'); and get function help to get all data from database.

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.


2 Answers

To sort by ASC: Laravel Docs - sortBy()

$collection->sortBy('field');

To sort by DESC: Laravel Docs - sortByDesc()

$collection->sortByDesc('field');

like image 161
Rodrigo Pauletti Avatar answered Oct 18 '22 03:10

Rodrigo Pauletti


Laravel 5

https://laravel.com/docs/5.8/collections#method-sortby

Laravel 4

https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_sortBy

Usage

$collection->sortBy('field', [], true); // true for descending
like image 43
Bishal Paudel Avatar answered Oct 18 '22 04:10

Bishal Paudel