2
I’m starting to Laravel 5
and as an apprenticeship I am creating a simple employee registration. What I need is to recover from the bank a relationship of employees with exams based on search conditions (filters).
In the example below, I used the When
to include the condition Where
if the official filter is filled.
$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 well. In another test I wish to seek the examinations of employees whose maturity is 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 the 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']);
The SQL Builder you did not bring the results or gave error?
– novic
Error: Methodnotallowedhttpexception in Routecollection.php line 233: However, if I change the Query to ->whereBetween('next_exam',[$data_start , $data_final]), removing the condition When everything works normally.
– L.B.O
Erro: MethodNotAllowedHttpException in RouteCollection.php line 233
what’s on that line?:– novic
Error is passing two variables on
when()
, only accept one. I have no way to test, so don’t post an answer, but see if it works if you separate things, something like that:->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 );
 })
– Evert
Ball show @Evert. Works perfectly, including with more parameters. You can answer the question please mark as answer. Thank you.
– L.B.O