Can I sort the groupBy Collection keys?

Posted 2 years ago by TonsOfLaz

Hi, I have a collection I wanted to group by a category, like so:

$my_objects->groupBy(function ($item, $key) {
                        if ($item->category) {
                            return $item->category->name;

That comes back correctly grouped, i.e:

  ['Government'] => [3 objects],
  ['Education'] => [12 objects]

But I need to display the categories in alphabetical order. I cannot for the life of me figure out how to sort these keys without manually doing it (which i can do, but i need to this elsewhere so would prefer not to). I don't want to convert to an array and use ksort either, because I need to have the objects still.

Is there an easy way to do this with Collections I am missing? Thanks in advance for any help.

Please sign in or create an account to participate in this conversation.