Hi, I'm fairly new to Laravel and I'm trying to solve the following problem:
Model Booking
start_date
end_date
I would like to retrieve information if a booking is in the past, active, or in the future through related models, e.g.
$customer->bookings->past, $customer->bookings->active, $customer->bookings->future
I do understand the concept of accessors but I was wondering if there was another way that makes sense in this scenario.
If you want to retrieve them from DB you can use relationship query
class Customer
{
public function specialBookings()
{
return $this->hasMany(Booking::class)->where(function($q){
$q->where('active', true)
->where('start_date', '<', now()) // For past
->where('start_date', '>', now()); // For future
});
}
}
Usage
$customer->specialBookings
But if you want to retrieve all bookings and then loop over them and do conditional statement, then the accessors is the way to go.
@MohamedTammam thank you, unfortunately it is not what I'm looking for. I want to re-use this from several different related tables and would like to avoid having to change the queries in those related models in case anything ever changes.
@katsu You don't need to change them, you can create multiple relationship with the same models with different conditions.
For Example
class Customer
{
public function bookings()
{
return $this->hasMany(Booking::class)
}
public function specialBookings()
{
return $this->hasMany(Booking::class)->where(function($q){
$q->where('active', true)
->where('start_date', '<', now()) // For past
->where('start_date', '>', now()); // For future
});
}
}