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

iluca89's avatar

Get number of occupied nights on Hotel System

Hello to everyone, I'm trying to get number of occupied nights in a given month for an Hotel System in Laravel.

In my DB I have arrival_date and departure_date. But if in the same date I have a checkout from one booking, and a checkin from on other one, I have to consider just one night.

I tried this, but it doesn't work:

public function occupancyRate()
{
    $startOfMonth = Carbon::now()->startOfMonth();
    $endOfMonth = Carbon::now()->endOfMonth();

 
    $totalNightsInMonth = $endOfMonth->diffInDays($startOfMonth) + 1; 

        $bookings = Booking::where(function ($query) use ($startOfMonth, $endOfMonth) {
        $query->whereBetween('arrival', [$startOfMonth, $endOfMonth])
            ->orWhereBetween('departure', [$startOfMonth, $endOfMonth])
            ->orWhere(function ($query) use ($startOfMonth, $endOfMonth) {
                $query->where('arrival', '<', $startOfMonth)
                    ->where('departure', '>', $endOfMonth);
            });
    })
    ->get();

$totalOccupiedNights = 0;

foreach ($bookings as $booking) {
    $arrival = Carbon::parse($booking->arrival);
    $departure = Carbon::parse($booking->departure);

    $nightsOfStay = $arrival->diffInDays($departure) + 1;

    $totalOccupiedNights += $nightsOfStay;
}

$occupancyRate = ($totalOccupiedNights / $totalNightsInMonth) * 100;

return $occupancyRate;
}
0 likes
2 replies
iluca89's avatar

I also though to add a local scope in my Booking controller and use it in my occupancyRate() function, but I didn't find the way. public function scopeCalculateNights(Builder $query) { return $query->selectRaw('*, DATEDIFF(departure, arrival) AS nights_of_stay'); }

Snapey's avatar

You need to find all bookings that start and end in the same month, start in the month and end outside the month, and start before the month and end in the month.

Probably unlikely but there is always the possibility that a booking started before the month start and ended after month end.

Then for each booking you need to count the number of days in the month.

Please or to participate in this conversation.