Hi,
I'm currently learning Laravel and am unclear about how to best approach the following scenario.
I'm using query builder with a when condition to filter conference rooms that are either free or booked for a certain date. Currently it looks like this:
->when($this->status === 'booked', fn($query) => $query->whereHas('reservations', function (Builder $query) {$query->where('start_date','<=', $this->date)
->where(function($query) {
$query->where('end_date', '>=', $this->date)
->orWhereNull('end_date');
});}))
->when($this->status === 'free', fn($query) => $query->whereDoesntHave('reservations', function (Builder $query) {$query->where('start_date','<=', $this->date)
->where(function($query) {
$query->where('end_date', '>=', $this->date)
->orWhereNull('end_date');
});}))
As I am using the same query in other places for displaying reservations for a room, etc. so I thought I'd create a function in my model that accepts date as an input but I failed to use it in my query above.
public function currentReservations($date)
{
return $this->hasMany(Reservation::class)
->where('start_date','<=', $date)
->where(function($query) use ($date) {
$query->where('end_date', '>=', $date)
->orWhereNull('end_date');
});
}
Any help is appreciated!
Thank you!