Advanced search in Laravel 5

2

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']);
    
asked by anonymous 24.06.2017 / 13:47

1 answer

3

The problem is in the amount of argument sent in the when() clause, which currently only accepts one.

One suggestion would be to break into two, as follows:

$exames = Employee_Exam::join('employees','employees.id','=','employee_exams.employee_id')
                    ->join('exams', 'exams.id', '=', 'employee_exams.exam_id')
                    ->when($data_inicio, function ($query) use ($data_inicio) {
                        return $query->where('next_exam', '>=', $data_inicio);
                    })
                    ->when($data_final, function ($query) use ($data_final) {
                        return $query->where('next_exam', '<=', $data_final);
                    })  
                    ->orderBy('employee_exams.next_exam', 'asc')
                    ->get(['employee_exams.*',
                           'employees.id', 
                           'employees.identidade', 
                           'exams.exame']
                     );

Success!

    
25.06.2017 / 14:10