If you have eager loaded the category with the Products, then you can groupBy('category.name')
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');
}
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
Please or to participate in this conversation.