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
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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);
}
}
)
$colors_array = ['red', 'green', 'blue'];
Foo::with('colors')->whereHas('colors', function ($query) use ($colors_array) {
$query->distinct()->whereIn('name', $colors_array);
}, '=', count($colors_array));
Please or to participate in this conversation.