Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

martinszeltins's avatar

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
  ]
}
0 likes
12 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102
$collection->sort(function($a, $b)  { 
    if ($a == $b) {
    return 0; 
    }
    return ($a > $b) ? -1 : 1; 
});
1 like
martinszeltins's avatar

@sinnbeck thanks, that worked! I don't understand why there isn't a sortDesc() method, it should be added to the framework.

JeffreyWay's avatar

There's a sortByDesc() method on the Collection instance.

1 like
Sinnbeck's avatar

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;
            });
        });
martinszeltins's avatar

@sinnbeck If I put that in a service container and then Laravel releases with a build-in sortDesc won't I have a conflict?

Sinnbeck's avatar

@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 😊

mooseh's avatar

@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;
    });
});
JChrisTyler's avatar

You can actually call sortBy or sortByDesc with null for the callback/key. So for a simple sortDesc you can just use sortByDesc(null)

3 likes

Please or to participate in this conversation.