How to check if a time period overlaps with another time period in PHP Laravel
P粉011360903
2023-09-03 00:18:11
<p>How to check if the working hours of a specific user for a given time period already exist in the database. Therefore, the function should return true when working hours overlap with the given date and time. I tried it but it doesn't work. </p>
<pre class="brush:php;toolbar:false;">function checkExistingWorkingHours($user_id, $start_date, $start_time, $end_date, $end_time)
{
// dd($user_id . " " . $start_date . " " . $start_time . " " . $end_date . " " . $end_time);
$startDateTime = Carbon::parse($start_date . ' ' . $start_time);
$endDateTime = Carbon::parse($end_date . ' ' . $end_time);
$overlapExists = WorkingHour::where('user_id', $user_id)
->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where(function ($query) use ($startDateTime, $endDateTime) {
// Check for overlap where the start_datetime is between existing start_datetime and end_datetime
$query->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '=', $startDateTime->format('Y-m-d'))
->where('start_time', '<', $endDateTime->format('H:i'))
->where('end_date', '=', $startDateTime->format('Y-m-d'))
->where('end_time', '>', $startDateTime->format('H:i'));
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '<', $startDateTime->format('Y-m-d'))
->where('end_date', '=', $startDateTime->format('Y-m-d'))
->where('end_time', '>', $startDateTime->format('H:i'));
});
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
// Check for overlap where the end_datetime is between existing start_datetime and end_datetime
$query->where(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '=', $endDateTime->format('Y-m-d'))
->where('end_date', '>=', $endDateTime->format('Y-m-d'))
->where('start_time', '<', $endDateTime->format('H:i'));
})->orWhere(function ($query) use ($startDateTime, $endDateTime) {
$query->where('start_date', '<=', $startDateTime->format('Y-m-d'))
->where('end_date', '>=', $endDateTime->format('Y-m-d'));
});
});
})->exists();
return $overlapExists;
}</pre>
<p>When I test the function with the following data, it says there is overlap even though there is no overlap. </p>
<p>Check existing working hours (1, 2023-06-01, 00:15, 2023-06-01, 03:00);</p>
<p>The value in the database is 2023-06-01 03:30 to 11pm. </p>
Try using this
Answer based on geertjanknapen's comment: