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

theharisshah's avatar

Check if all the related hasMany models have have certain value.

I have a Booking model which has hasMany relation called rooms, I want to check if all the rooms of that booking have status true, How can I do that in eloquent? I have come up with counting all the rooms in the booking model and getting the count of all the rooms with the status true and comparing the count. Is there any better solution?

0 likes
4 replies
dunas's avatar

You can use whereHas:

$roomsWithTrueStatus = App\Booking::whereHas('rooms', function ($query) {
    $query->where('status', '=', true);
})->count();
theharisshah's avatar

@DUNAS - I need to check if all the rooms have status true, this will only get me rooms who have status true.

AliceGray's avatar
Level 1

You can use every method on your rooms relation

every()

The every method may be used to verify that all elements of a collection pass a given truth test:

collect([1, 2, 3, 4])->every(function ($value, $key) {
   return $value > 2;
});

// false
staudenmeir's avatar

You can use whereDoesntHave():

Booking::whereDoesntHave('rooms', function ($query) {
    $query->where('status', '=', false);
})->get();

Please or to participate in this conversation.