I have a query for date range in Laravel that brings me to my head. Initially the query works without errors but I have detected that if the date range is between different years (12-2020 to 01-2021) it does not return any records. I'm a little tired of checking the code and I don't see the problem.
I put here the query that saves the data in an array and the check that I do later to apply the filter of the dates before returning the values.
public function getData($filters) {
$tasks = $this->getModel()
->whereIn('tasks.department_id', $filters['departmentIds'])
->join('departments', 'departments.id', '=', 'tasks.department_id')
->join('deliverables as dev', 'dev.id', '=', 'tasks.deliverable_id')
->leftJoin('deliverables as sub', 'sub.id', '=', 'tasks.subdeliverable_id')
->leftJoin('workers as st_workers', 'st_workers.id', '=', 'tasks.start_worker_id')
->leftJoin('workers as end_workers', 'end_workers.id', '=', 'tasks.end_worker_id')
->leftJoin('type_task_statuses', 'type_task_statuses.id', '=', 'tasks.status_id')
->leftJoin('incidences', 'incidences.task_id', '=', 'tasks.id')
->select('tasks.id', 'departments.name as department', 'tasks.start_worker_id', 'tasks.end_worker_id', 'st_workers.short_name as start_worker',
'end_workers.short_name as end_worker', 'tasks.plane', 'tasks.st', 'dev.name as deliverable', 'sub.name as subdeliverable',
'tasks.quantity', 'tasks.other_deliverable', 'tasks.start_prevision_date', 'tasks.end_prevision_date', 'tasks.start_date',
'tasks.end_date', 'tasks.prevision_hour', 'tasks.incurred_hour', 'type_task_statuses.display_name as status', 'type_task_statuses.color', 'tasks.advance', 'tasks.agreed',
'tasks.disagreed_date', 'tasks.supervised', DB::raw('COUNT(incidences.id) as count_incidences'))
->groupBy('tasks.id');
if (array_key_exists('fromDate', $filters) && $filters['fromDate']) {
$tasks->whereRaw('(DATE_FORMAT(tasks.end_date, "%m-%Y") >= "'.$filters['fromDate'].'" OR tasks.end_date is NULL)');
}
if (array_key_exists('toDate', $filters) && $filters['toDate']) {
$tasks->whereRaw('(DATE_FORMAT(tasks.end_date, "%m-%Y") <= "'.$filters['toDate'].'" OR tasks.end_date is NULL)');
}
return $tasks;
}