I'm starting at Laravel 5
and as learning I'm creating a simple employee's register. What I need is to retrieve from the bank an employee relationship with surveys based on search conditions.
In the example below, I used When
to include the condition Where
if the employee filter is populated.
$employees = Employee_Exam::join('employees', 'employees.id', '=', 'employee_exams.employee_id')
->distinct()
->when($id_employee, function ($query) use ($id_employee) {
return $query->where('employees.id', $id_employee);
})
->orderBy('employees.nome', 'asc')
->get(['employees.id','employees.nome', 'employees.identidade', 'employees.company_id']);
This works perfectly. In another test I want to fetch the employee exams that are due between the start and end dates defined through the search filter.
My question is how to use the same idea of When
for more than one condition in Where
. I tried the code below but without success.
$exames = Employee_Exam::join('employees', 'employees.id', '=', 'employee_exams.employee_id')
->join('exams', 'exams.id', '=', 'employee_exams.exam_id')
->when($data_inicio, $data_final, function ($query) use ($data_inicio, $data_final) {
return $query->whereBetween('next_exam',[$data_inicio , $data_final]);
})
->orderBy('employee_exams.next_exam', 'asc')
->get(['employee_exams.*','employees.id', 'employees.identidade', 'exams.exame']);