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?
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.
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.
To sort by ASC: Laravel Docs - sortBy()
$collection->sortBy('field');
To sort by DESC: Laravel Docs - sortByDesc()
$collection->sortByDesc('field');
https://laravel.com/docs/5.8/collections#method-sortby
https://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html#method_sortBy
$collection->sortBy('field', [], true); // true for descending
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With