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

kachi_dk's avatar

I want to check aganist array of values in a query

I have an array of values I want to check against in a query, so far this was how I looped it. But It doen't seem to work.

$provider = User::query()
            ->where('user_type', 'admin')
            ->whereRelation('tag', function ($query) use ($followedTags) {
                $query->whereJsonContains('names', $followedTags[0]);

                for ($i = 1; $i < count($followedTags); $i++) {
                    $query->whereJsonContains('names', $followedTags[$i]);
                }
                return $query;
            })
            ->paginate();
0 likes
3 replies
rodrigo.pedra's avatar
Level 56

Do you want a user that contains all tags provides, or that contains any of the tags provided?

If any, you could try using ->orWhereJsonContains() to test for each tag.

$provider = User::query()
    ->where('user_type', 'admin')
    ->whereRelation('tag', function ($query) use ($followedTags) {
        $query->where(function ($query) use ($followedTags) {
            foreach ($followedTags as $tag) {
                $query->orWhereJsonContains('names', $tag);
            }
        });
    })
    ->get();

The extra ->where() with a closure, is to wrap all OR WHERE clauses into parenthesis to avoid conflicts with other WHERE clauses.

Please or to participate in this conversation.