If I have an Illuminate\Support\Collection, how do I sort by multiple properties with both asc and desc? (This is a simple hypothetical - not at all looking for tips on query building.)
$collection = User::all(); // not looking for User::orderBy()->get() solutions. Read the question.
$sorting_insructions = [
['column'=>'first_name', 'order'=>'asc'],
['column'=>'date_of_birth', 'order'=>'desc'],
];
$collection->sort(function($a,$b) use ($sorting_instructions){
// something...
});
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.
Laravel Pluck() is a Laravel Collections method used to extract certain values from the collection. You might often would want to extract certain data from the collection i.e Eloquent collection.
Laravel collections can be regarded as modified versions of PHP arrays. They are located in the Illuminate\Support\Collection directory and provide a wrapper to work with data arrays. In the code snippet above, we used the collect() method to create a Collection instance from the defined array.
$coll = User::all(); echo $coll->count();
I know this question is from a while back, but in case anyone stumbles across it, Laravel does provide this functionality now (v8.x at the time of writing).
See the official docs for more detail. (4th code block example in the sort-by section) https://laravel.com/docs/8.x/collections#method-sortby
From the docs:
If you would like to sort your collection by multiple attributes, you may pass an array of sort operations to the sortBy method. Each sort operation should be an array consisting of the attribute that you wish to sort by and the direction of the desired sort:
$collection = collect([
['name' => 'Taylor Otwell', 'age' => 34],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Abigail Otwell', 'age' => 32],
]);
$sorted = $collection->sortBy([
['name', 'asc'],
['age', 'desc'],
]);
$sorted->values()->all();
/*
[
['name' => 'Abigail Otwell', 'age' => 32],
['name' => 'Abigail Otwell', 'age' => 30],
['name' => 'Taylor Otwell', 'age' => 36],
['name' => 'Taylor Otwell', 'age' => 34],
]
*/
Applied to the example from the question:
/*
$sorting_instructions = [
['column'=>'first_name', 'order'=>'asc'],
['column'=>'date_of_birth', 'order'=>'desc'],
];
*/
$collection = User::all();
$sortedCollection = $collection->sortBy([
['first_name','asc'],
['date_of_birth','desc'],
])
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