php – $query->where in many to many relationship-ThrowExceptions

Exception or error:

In my controller I setup two filters one for category (has-one relationship)
and one for shop (many to many relationship)

public function products($filter = NULL, $key = NULL)
{
    $query = Product::query();
    $query = $query->where('status', '=', 1);
    if ($filter === 'category') {
        $cat = Category::where('slug', '=', $key)->select('id')->firstOrFail();
        $query = $query->where('category_id', '=', $cat->id);
    }
    if ($filtro === 'shop') {
        $shop = Shop::where('slug', '=', $key)->select('id')->firstOrFail();
        // HOW TO ADD HERE A WHERE IN MANY TO MANY RELATIONSHIP*
    }
    $products = $query->whereNotNull('startdate')->with('shops', 'categories')->orderby('startdate')->get();

*HOW TO ADD to the query A WHERE IN MANY TO MANY RELATIONSHIP only if “shop” filter are set?

How to solve:

Use the whereHas() method like this:

$query->whereHas('shops', function($q) use($shop) {
   $q->where('id', $shop->id); 
});

Define the shops relationship in the Product model to make this work.

Leave a Reply

Your email address will not be published. Required fields are marked *