'Query to get available slot from appointments table

I have employees, working_hours, & appointments table. with the following details:

Employees | working_hours                                                     | appointment
id, name  | id, day, start_time, end_time, employeeable_id, employeeable_type | id, employee_id, start_date_time, end_date_time

Relation:

class Employee extends Model
{
   public function workingHours()
   {
      return $this->morphMany(WorkingHour::class, 'employeeable');
   }
}

class WorkingHour extends Model
{
   public function employeeable()
   {
      return $this->morphTo();
   }
}

class Appointment extends Model
{
   public function employee()
   {
      return $this->belongsTo(Employee::class);
   }
}

Employee A has the following working hours:

[
   { day: 1, start_time: '08:00:00', end_time: '17:00:00' },
   ...
   { day: 5, start_time: '08:00:00', end_time: '17:00:00 }
]

Employee A has an appointment on May 23, 2022 09:00:00 till 09:30:00 (each appointment duration is 30 minutes)

Question:

If admin requests for available slots from May 22, 2022 to June 1, 2022 for Employee A, I expect response like this:

[
   { '2022-05-22': ['08:00', '08:30', '09:00', ..., '17:00'] },
   { '2022-05-23': ['08:00', '08:30', '09:30'] } // 09:00 notice excluded.
   ...
   { '2022-06-01, [] }
]

How to define the above query? All I can think of is to loop every working hours time from employee A and check if the time is available or not.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source