Giacomo
Giacomo

Reputation: 341

Laravel | How to display attributes assigned to products in category view

I have problem with relationship query. I have in my show.blade.php (category):

@foreach( $attributes as $attribute)
 {{ $attribute->title }}
@endforeach

and in CategoryController function show:

$attributes = Attribute::where('visible',1)
        ->orderBy('order', 'asc')
        ->with('products')
        ->get();

I need to display product attributes for specific categories. Solution displaying all attributes from the database. I have 3 categories, each of these categories has products that have their own attributes. Not all attributes are in all categories.

My model relationship is: Category 1:n Product N : (pivot product_attribute) : N Attribute

Category id is passed from the view. I also have access to a specific category. But how to display the attributes of products in this category. Do you have any idea?

Upvotes: 2

Views: 1075

Answers (1)

Khushbu
Khushbu

Reputation: 735

Assuming you have relationships defined properly in Attribute and Product models, You can use below query to get Attributes of specific category

$attributes = Attribute::with(['product.category'])->whereHas('product.category', function($q) use ($categoryId) {
  $q->where('id', $categoryId);
})->get();

Here product is relation name defined in Attribute model and category is relation name defined in Product model. id is primary key field in category table.

Upvotes: 4

Related Questions