How to sort a collection in descending order? Laravel collections has a sort() method to sort a collection (but only in ascending order). Unfortunately I can't find a way to sort in a descending order. There is no sortDesc() method and the sort method doesn't allow to pass a descending parameter.
Any help would be much appreciated.
I can only sort it in ascending order...
$sorted = $collection->sort();
Result:
Collection {#1884
#items: array:10 [
"GTA 5" => 1
"CS" => 1
"Trackmania" => 1
"Doom" => 3
"Quake Live" => 4
"NHL" => 5
]
}
$collection->sort(function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});
@sinnbeck thanks, that worked! I don't understand why there isn't a sortDesc() method, it should be added to the framework.
There's a sortByDesc() method on the Collection instance.
Put this in a service provider :)
Collection::macro('sortDesc', function () {
$this->sort(function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});
});
@sinnbeck If I put that in a service container and then Laravel releases with a build-in sortDesc won't I have a conflict?
@martinzeltin yes but I am unsure of how it will handle it. For fun you could overwrite another method and see if laravel blows up 😊
@sinnbeck your macro is returning nothing, make sure it returns something :D
Collection::macro('sortDesc', function () {
return $this->sort(function($a, $b) {
if ($a == $b) {
return 0;
}
return ($a > $b) ? -1 : 1;
});
});
You can actually call sortBy or sortByDesc with null for the callback/key. So for a simple sortDesc you can just use sortByDesc(null)
Please sign in or create an account to participate in this conversation.