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

devondahon's avatar

Make a query where a relationship matches all elements of an array

How to make a query that will only return the Foo elements containing all the given colors (from $colors_array) in its relationship colors, and not the results containing one of the listed colors like below ?

$colors_array = ['red', 'green', 'blue'];

Foo::with('colors')
->whereHas(
    'colors',
    function ($query) use ($colors_array) {
        if ($filters) {
            $query->whereIn('name', $colors_array);
        }
    }
)
0 likes
2 replies
MichalOravec's avatar
Level 75
$colors_array = ['red', 'green', 'blue'];

Foo::with('colors')->whereHas('colors', function ($query) use ($colors_array) {
    $query->distinct()->whereIn('name', $colors_array);
}, '=', count($colors_array));
2 likes
devondahon's avatar

@michaloravec That's exactly what I needed, thanks a lot !

However I'm surprised how slow the queries are. Is there any faster alternative ?

Please or to participate in this conversation.