I
I
Igor T2020-06-25 19:31:28
Laravel
Igor T, 2020-06-25 19:31:28

How to get products in a category by condition?

Good day!
I have a project in Laravel. I will describe it in a simplified way to understand only the problem.
There are tables in the database:
categories - categories of goods;
products - products (category_id is specified in the products table);
filters - product properties (manufacturer, material, diameter, etc.)
filter_items - possible values ​​of these properties (Tefal, Rowenta, LG) with binding which value to which filter;
category_filters - which filters are specific to each category (for example, for frying pans, this is the manufacturer, diameter and presence of a handle)
product_filter_items - these are the specific properties of each product.

I get the category in the controller:

$category = Category::find($id);
return view('category', compact('category'));

In the view, I need to display a list of filters specific to this category and in each filter the available values ​​(that is, only those that are inherent in at least one product from this category, i.e. are in the product_filter_items table).
But for now, I'm displaying all possible values.
@foreach($category->filters as $filter)
<h3>{{$filter->name}}</h3>
@foreach($filter->items as $item)
<input type="checkbox" name="filters[{{$filter->id}}][]" id="check{{$item->id}}">
<label for="check{{$item->id}}">{{$item->name}}</label>
@endforeach
@endforeach

Something like this:
5ef4cf9998419651150365.png
How would I exclude those values ​​that do not belong to any product?
I tried to write in the Filter model:
public function getCatItemsAttribute($category_id){
//здесь бы я по $category_id достал только нужные значения
//return ......
    }

so that you can iterate in the view like this:
@foreach($filter->сatItems as $item)
<input type="checkbox" name="filters[{{$filter->id}}][]" id="check{{$item->id}}">
<label for="check{{$item->id}}">{{$item->name}}</label>
@endforeach

Can I somehow pass the category id to getCatItemsAttribute? type
$filter->сatItems($category->id) as $item

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question