Laravel Eloquent Relationship Like Query I am trying to query categories where product tags is equal to user selected tags in filter bar , Here is the query what I have tried so far :
$categories = Category::with('products');
// selected tags is array which contain tags
if (! empty($selectedTags)) {
foreach ($categories->get() as $category) {
$categories = $category->whereHas('products', function ($query) use ($selectedTags) {
foreach ($selectedTags as $tag) {
$query->where('tags','LIKE','%'.$tag.'%');
}
});
}
}
$categories = $categories->distinct()->paginate(3);
Please note that tags column in product table is comma separated values that's why I am trying to access it via like query .
@sr57 Yes I have used orWhere on the same query but no luck
@sr5 I am using laravel debugbar and it gives me following query
select distinct * from categories where exists (select * from products where category.id = products.category_id or (tags LIKE '%Popular%' or amenties LIKE '%Newest%')) limit 3 offset 0
Why are you running a query there?
$categories->get()
That means you get every single category from the database..
I would assume you doing something like this
$categories = Category::with('products')->whereHas('products', function ($query) use ($selectedTags) {
foreach ($selectedTags as $tag) {
$query->orWhere('tags','LIKE','%'.$tag.'%');
}
})->paginate(3);
@Sinnbeck Actually in further development I need more filtration functions that's why I just load the model and query like that way .
@khizerdev then add those filters to the query builder. Use my example as a base and show what else you need
Please sign in or create an account to participate in this conversation.