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

evlonmop's avatar

Get id column for a nested hasMany() relation

I have a working query but obviously it looks ugly and sure it can be much optimized.

I'm looking for booked rooms inside a range of dates, then I calc the difference with total hotel rooms and I get the available room ids for booking those dates.

        // 1. get desired dates
        $from = Carbon::parse(request()->arrival_at);
        $to = Carbon::parse(request()->departure_at);

        // 2. get all reservations
            // that finish inside the range plus arrival 1 day
            // that ends inside the range minus 1 day
        $reservations = Reservation::with('stays.room')
            ->whereBetween('arrival_at', [$from->subDay(), $to])
            ->orWhereBetween('departure_at', [$from, $to->addDay()])
            ->get();

        // 3. get which rooms these reservations need
        $roomsReserved = [];
        foreach ($reservations as $r) {
            foreach ($r->stays as $s) {
                $roomsReserved[] = $s->room_id;
            }
        }

        // 4. get available rooms ids
        return Room::whereNotIn('id', array_unique($roomsReserved))->pluck('id');

How can I get the $reservation->stays()->room->id in the same query?

0 likes
1 reply
staudenmeir's avatar

I would leave it like this. A single combined query would be more complicated but not necessarily faster.

What you can easily improve:

$roomsReserved = $reservations->pluck('stays')->flatten()->pluck('room_id');
1 like

Please or to participate in this conversation.