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'); }
Apr 16, 2024
2
Level 1
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;
}
Please or to participate in this conversation.