In this episode, we dive into how to add employee schedule availability to our application. Starting off, we discuss why it's important to check not just the requested dates, but whether the employee is actually available to work on each of those days. To do this, we update our class to accept an employee and the relevant service right in the constructor.
We do a quick demo by pulling an employee and a service from the database so we can play around with real data. With these in place, we start iterating over the requested period and look up whether the employee is scheduled to work on each day. The focus here is on being efficient—we avoid making a database query for each day, instead using Laravel collections to filter out the days that fit inside the schedule.
Next, we look at how to grab the working hours for a specific date. Using a bit of dynamic magic, we can access the start and end times for any day of the week based on column names in the database. We address some edge cases too, like what happens if there's no schedule or if the employee simply doesn't work on a particular day.
With the working hours in hand, we then add these periods to our collection of availabilities. We make sure to carefully copy and set the time for each period, being wary of mutating the original date objects—an important gotcha when dealing with dates in PHP. By the end, we have a full list of all the time periods the employee can work within the requested date range.
But, before we're done, we have to factor in how long the requested service actually takes. It wouldn't make sense to allow an appointment to start right when the shift ends, so we subtract the service duration from the latest possible appointment start time for each slot. With this, we wrap up with a proper collection of actual available time slots for the employee, based on their schedule and the specifics of the service. Generating the actual bookable slots comes next, but now we've got all the right periods in place!