Search code examples
magentolaraveleloquentlayered-navigation

Laravel: how to filter eloquent data by relationships


I'm building a product catalog in laravel and I would like to filter the products based on their attributes.

I have 2 tables, Products & Attributes. Attributes have a key, value and product_id. For example:

product_id - key   - value
12         - brand - BestBrandEver
23         - brand - EvenBetterBrand

Now I would like to be able to filter down my products via a form on the category page which passes query string parameters like "brand=BestBrandEver or brand=EvenBetterBrand" and retrieve only the products from that brand. Eventually I would like to do the same with color, material etc... It's much like Magento's or Woocommerce layered navigation.

I'm stuck for a while now because I don't know how to start building this the right way. Is there someone who could help me with this or is able to point me in the right direction (maybe even with a tutorial or video)?

Thanks in advance!


Solution

  • Assuming a url like this:

    /products?filters[brand][]=a&filters[brand][]=b&filters[color][]=a&filters[color][]=b
    

    and so forth...


    Use the whereHas method to restrict your products by their attributes:

    Product::whereHas('attributes', function ($query) {
        foreach (Input::get('filters') as $key => $values) {
            $query->orWhere(function($query) use ($key, $values) {
                $query->where('key', $key)->whereIn('value', $values);
            });
        }
    });