So you want the category names to also be sorted? Maybe just use sort()?
$groups = $collection->groupBy('category.name')->sort();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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.
What about if you reverse the order of sortBy and groupBy?
$groups = $collection->sortBy(category.name)->groupBy('category.name');
Please or to participate in this conversation.