Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

khizerdev's avatar

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 .

0 likes
7 replies
khizerdev's avatar

@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

Sinnbeck's avatar

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);
khizerdev's avatar

@Sinnbeck Actually in further development I need more filtration functions that's why I just load the model and query like that way .

Sinnbeck's avatar

@khizerdev then add those filters to the query builder. Use my example as a base and show what else you need

Please or to participate in this conversation.