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

tvbz's avatar
Level 4

How to query to match all in array?

Hi,

I'm having some trouble getting my eloquent query right. Let's say I have an array of ID's:

$features_array = [1, 4, 6]

Using a whereIn() as below, I've build a query that returns items that match any ID in the $features_array. But how would you get only the items that have all features in the array?

Items::select('*')
    ->when($features, function ($query, $features) {
        return $query->whereHas('features', function ($query) use ($features) {
            $query->whereIn('id', $features);
        });
    })->distinct()->get();

Thanks

0 likes
2 replies
tvbz's avatar
Level 4

I managed to get the desired result using a foreach loop inside the subquery. Is this a good fix or is there a more 'eloquent' solution?

Items::select('*')
    ->when($this->features, function ($query, $features) {
        foreach($features as $f) {
            $query->whereHas('features', function ($query) use ($f) {
                $query->where('features.id', $f);
            });
        };
    })->distinct()->get();

Thanks

MichalOravec's avatar

@tvbz This should work:

Items::when($this->features, function ($query, $features) {
    $query->whereHas('features', function ($query) use ($features) {
        $query->distinct()->whereIn('id', $features);
    }, '=', count($features));
})->get();

Please or to participate in this conversation.