2 months ago

Eloquent : Scope whereIn matches all (relation)

Posted 2 months ago by FrankClark

Hello There,

I have a table rooms And a table room_availabilities

A room has many room room_availabilities with foreign key room_id

A room availability basically made up of room_id and date. There is an entry for each available date for that room.

I want to have query scope that checks to see if all dates in an array are available and will only return the room if all dates are available. What do I need to do to achieve this. The below obviously won't have the desired effect because it will just return the rooms where it has one of those dates. I want it to match all of them or exclude the room.

 public function scopeAvailableBetween(Builder $query, $dates): Builder
        $startDate = $dates[0];
        $endDate = $dates[1];
        $periodDates = CarbonPeriod::create($startDate, $endDate);
        $datesBetween = [];
        foreach ($periodDates as $date) {
            $datesBetween[] = $date->format('Y-m-d');

        $query->with('roomAvailabilties')->whereIn('', $datesBetween);

Please sign in or create an account to participate in this conversation.