Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

moctarss's avatar

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)?

0 likes
2 replies
moctarss's avatar

Thank you for pointing me out. I just want to ask, is it possible to use Model::leftJoin + when? What if i want to access the model via its connection example $child->parent->someObject->someField? Since i used join/leftJoin/RightJoin is it still possible to get the connection?

Please or to participate in this conversation.