Hi all!
I received a collection of products that contains many-to-many relationships.
The question is how to select only those products from this collection that match my request. For example, only those who have id color 1 or 2, id brand 1?
dd($products);
Illuminate\Database\Eloquent\Collection {#1843 ▼
#items: array:7 [▼
0 => App\Models\Product {#1652 ▼
#fillable: array:17 [▶]
...
#attributes: array:20 [▶]
...
#relations: array:9 [▼
"brands" => Illuminate\Database\Eloquent\Collection {#1734 ▼
#items: array:1 [▼
0 => App\Models\Brand {#1751 ▼
...
#attributes: array:12 [▼
"id" => 1
"title" => "adidas"
...
]
}
]
"colors" => Illuminate\Database\Eloquent\Collection {#1734 ▼
#items: array:2 [▼
0 => App\Models\Color {#1751 ▼
...
#attributes: array:12 [▼
"id" => 1
"title" => "red"
...
1 => App\Models\Color {#1751 ▼
...
#attributes: array:12 [▼
"id" => 2
"title" => "blue"
...
]
...
}
]
...
}
...
}
1 => App\Models\Product {#1651 ▶}
2 => App\Models\Product {#1650 ▶}
I tried that, but it didn't work.
$filter = $products->
whereIn('colors.id', ['1', '2'])
->whereIn('brands.id', ['1'])
->paginate('100');
$filter = $products
->filter(function ($query){
return $query->whereIn('brands.id', ['1']);
})
->filter(function ($query){
return $query->whereIn('colors.id', ['1', '2']);
})
->paginate('100');