Filters for different categories using many-to-many relationship

Posted 7 months ago by kaleopter

Hello! I have a problem with many-to-many relationship.

I have different categories and products (ex. mobile phones, notebooks and wacuum cleaners) and each category has its own filters with values (ex. mobile phones - screen diagonal and wacuum cleaners - suction power). I don't want to store all of the filters in my products table, cause there will be a lot of empty cell in it. My idea is:

I have categories, products, filters and filter_product tables in my DB.


id | name


id | vendor | name | ... | category_id


id | name | measure | category_id


id | filter_id | product_id | value

In the view category.blade.php I display only filters belongs to current category - than works nice.

@foreach($category->filters  as $filter)
    <h6>{{ $filter->name }}</h6>

Further, I want to display filter_product.value in checkboxes here. I try to do it with many-to-many relationship.

In my Filter class:

public function products()
        return $this->belongsToMany(Product::class);

In my Product class:

public function filters()
        return $this->hasMany(Filter::class);

In category.blade.php:

@foreach($category->filters  as $filter)
    <h6>{{ $filter->name }}</h6>
    @foreach($filter->products as $product)
        <li>{{ $product->value }}</li>

And here I get as many li elements as lines in filter_product table. But I can't get value. I have only

"pivot_filter_id" => 1
"pivot_product_id" => 1

Is my idea correct, or absolutely not? How can I get value from filter_product?

Thanks for help))

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.