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

matus's avatar
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

0 likes
0 replies

Please or to participate in this conversation.