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

katsu's avatar
Level 1

Can this be solved other than through accessor?

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.

Edit: I'm using Laravel 9

0 likes
4 replies
MohamedTammam's avatar

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.

katsu's avatar
Level 1

@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.

MohamedTammam's avatar

@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
        });
    }
}
katsu's avatar
Level 1

@MohamedTammam I see where you are coming from. Thank you. I decided to use an accessor as it gives me more flexibility to work with the data

Please or to participate in this conversation.