Jun 26, 2016
0
Level 2
Many to many - multiple filters
Hello,
I've got a model with 3 many to many relationships. Think of it as an Article model with 3 different tables for tags. These tags represent 3 different categories. I would like to filter these articles based on 3 selects each for one category of tags. Is there a more efficient or cleaner way of doing this?
This is my current code:
$query = Item::query();
$categories1 = ['example1', 'example2'];
$categories2 = ['example1', 'example2'];
$categories3 = ['example1', 'example2'];
foreach ($categories1 as $tag)
{
$query->whereHas('category1', function ($q) use ($tag) {
$q->where('name', $tag);
});
}
foreach ($categories2 as $tag)
{
$query->whereHas('category2', function ($q) use ($tag) {
$q->where('name', $tag);
});
}
foreach ($categories3 as $tag)
{
$query->whereHas('category3', function ($q) use ($tag) {
$q->where('name', $tag);
});
}
return $query->get();
Thank you
Please or to participate in this conversation.