Support the ongoing development of Laravel.io →
posted 9 years ago
Eloquent

I have a collection of products. Each product is assigned to a category. I am using ->with(productFromCategory) to get a collection of all my products, as well as their category relationship.

How can I sort the collection first by Category, and then by products within those categories.

I can do the first part

$products = $productsCollection->sortBy('productFromCategories.category_name');

That returns my products sorted by categories.

But then the products are not sorted by product_name inside their respective categories.

Is there a way to sort the products relative to their categories now in that collection?

Last updated 3 years ago.
0

Sign in to participate in this thread!

PHPverse

Your banner here too?

Nertskull nertskull Joined 3 Apr 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2025 Laravel.io - All rights reserved.