Abdo Rabah
Abdo Rabah

Reputation: 2072

Filter pivot table in Laravel?

Is there a way to add a where clause on one of the tables of the pivot table inside the pivot table ? For example in the code below, how can i add a where clause in products_categories to specify the products with type='ELECTRONICS' ?

DB::table("products_categories")
    ->whereIn("category_id", array_values($ids))
    ->pluck("id")
    ->all();

Upvotes: 0

Views: 79

Answers (1)

vahid zolfaghari
vahid zolfaghari

Reputation: 91

Try this:

$type = "ELECTRONICS";
$products_categories = Product::with('categories')->whereHas('categories', function($q) use ($type){
    $q->where('type', "%$type%");
})->get();

Upvotes: 1

Related Questions