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

FelixR's avatar

Sorting products by category

Hi everybody,

I'm pretty new to Laravel, but I'm already loving it! This is my problem:

I have a collection of products. They belong to 1 category. The field that references that id is called "product_category_id". Before I pass the collection to a view I call the groupBy('product_category_id') on the collection. Now what I want is the following:

  • Category name
    • Product 1
    • Product 2
  • Category 2 name
    • Product 3
    • Product 4

The product are showing just fine, it's the category name that's the issue. I searched for a solution in the docs, but I couldn't find one.

This is my view:

@foreach($grouped_products as $products)

   {{ product category name }}

   @foreach($products as $product)
                                           
       {{ $product->name }}  

   @endforeach
@endforeach

This is part of my product model:

   /**
    * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
    */
   public function categories()
   {
       return $this->belongsTo('App\ProductCategory', 'product_category_id');
   }

This is part of my ProductCategory model:

   /**
    * @return \Illuminate\Database\Eloquent\Relations\HasMany
    */
   public function products()
   {
       return $this->hasMany('App\Product');
   }

0 likes
7 replies
tykus's avatar

If you have eager loaded the category with the Products, then you can groupBy('category.name')

FelixR's avatar

Wow, that was pretty easy, thank you! :)

FelixR's avatar

This will sound silly, but how do I get the name of the cateogry? I tried $products->id and $products->name but none of them work.

FelixR's avatar

I'm aware this works in the second foreach. But that doesn't work for the collection of a cateogry with all its products.

@foreach($grouped_products as $products)

   {{ products->categories->name }} // <-- This doens't work

   @foreach($products as $product)
                                           
       {{ $product->name }}  
       {{ $product->categories->name }} // <-- This works ofcourse.

   @endforeach
@endforeach

I need to get the value of the identifier of the collection.

tykus's avatar
tykus
Best Answer
Level 104

Ah, silly me... looking at the question that was asked rather than critically evaluating what was being done.

You should fetch the categories and iterate over them, in the outer loop, and then the individual category products in the inner loop

// controller
$categories - Category::with('products')->get();


// view
@foreach ($categories as $category)
    {!! $category->name !!}
    @foreach ($category->products as $product)
        {!! $product->name !!} 
    @endforeach     
@endforeach
1 like
FelixR's avatar

Well, silly me too! That makes so much more sense then the other way around, thanks @tykus_ikus for your help!

Please or to participate in this conversation.