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

Ticked's avatar

Collection - orderBy / sortBy

Hi,

I have some items that belongs to some categories, the following code gives me the items grouped in their categories, the items are sorted ASC. I want also the categories to be sorted in ASC.

    public function itemsList()
    {
        $collection = Item::with('category')->where('status', 1)->orderBy('name', 'ASC')->get();
        $groups = $collection->groupBy('category.name');

        return view('pages.items.list', compact('collection', 'groups'));
    }

I tried... with no luck...

    public function itemsList()
    {
        $collection = Item::with('category')->where('status', 1)->orderBy('name', 'ASC')->get();
        $groups = $collection->groupBy('category.name')->sortedBy(category.name);

        return view('pages.items.list', compact('collection', 'groups'));
    }

Please any advice will be much appreciated.

0 likes
5 replies
zachleigh's avatar

So you want the category names to also be sorted? Maybe just use sort()?

$groups = $collection->groupBy('category.name')->sort();
Ticked's avatar

Hi @zachleigh,

Thank you for your time... your advice sorts the data in a different way, not by the name of the category or its id...

zachleigh's avatar
Level 47

What about if you reverse the order of sortBy and groupBy?

$groups = $collection->sortBy(category.name)->groupBy('category.name');
2 likes
Ticked's avatar

Hi...

I did not noticed that the solution has the categories in ASC but the items are not in ASC any more...

public function itemsList()
    {
        $collection = Item::with('category')->where('status', 1)->orderBy('name', 'ASC')->get();
        $groups = $collection->sortBy('category.name')->groupBy('category.name');

        return view('pages.items.list', compact('collection', 'groups'));
    }

Please or to participate in this conversation.