What about convert your query to an Eloquent query and use the when function.
Dec 8, 2019
2
Level 1
How to conditionally add query in Eloquent?
Considering this database design: Employee hasMany Contract, In reverse Contract belongs to an Employee and also Contract belongsTo Job and Department. Now I have this query:
$query = "SELECT DISTINCT e.*, con.*, job.name AS job_name, dept.name AS dept_name FROM employees e LEFT JOIN contracts con ON e.id = con.employee_id LEFT JOIN departments dept ON con.department_id = dept.id LEFT JOIN jobs job ON con.job_id = job.id WHERE 1=1 AND con.states LIKE 'Running'"
I also have additional query such that if some condition are met i will add it to my query, example
if($request['nationality']){ //If the user also includes employee's nationality as additional filter
$query .= " AND e.nationality LIKE ?";
array_push($bind, $request['nationality']);
}
if($request['job']){//If user also includes job as filter
$query .= " AND job.name LIKE ?";
array_push($bind, $request['job']);
}
...
at the end i collect my query like this: $employees = DB::select($query, $bind);, so far this works fine but i how would i implement it in a fully eloquent (without using traditional sql query)?
Please or to participate in this conversation.