$products->join('product_attributes as pa' . $attribute, function ($join) use ($attribute) { $join->on('pa' . $attribute . '.product_id', '=', 'products.id'); }); $products->where(function ($query) use ($attribute, $option) { $query->where('pa1.attribute_id', '=', 1); $query->where('pa1.attribute_option_id23', '=', 1); }); $products->where(function ($query) use ($attribute, $option) { $query->where(function ($query) use ($attribute, $option) { $query->where('pa3.attribute_id', '=', 3); $query->where('pa3.attribute_option_id', '=', 5); }); $query->orWhere(function ($query) use ($attribute, $option) { $query->where('pa3.attribute_id', '=', 3); $query->where('pa3.attribute_option_id', '=', 6); }); });