brianfr82 brianfr82 - 6 months ago 32
PHP Question

Laravel Eloquent where clause being ignored

I have the following query:

$owned = ['leads.user_id' => $this->crmUser->id, "leads.delegated_user_id" => null];
$delegated = ['leads.delegated_user_id' => $this->crmUser->id];

$leads = \Lead::where($owned)
->where("leads.status", "!=", "Archived")
->orWhere($delegated)
->where("leads.status", "!=", "Archived")
->rightJoin("tasks", "tasks.lead_id", "=", "leads.id")

->where('tasks.due_date', '<', date("F j, Y", strtotime('-10 days')))
->where("tasks.completed_at", null)
->get()->toArray();

\Log::debug(var_export($leads, true));


But the...

->where("tasks.completed_at", null)


Is being ignored. I'm a novice developer and I don't really understand why this is the case. I thought that that clause should apply to all the logic preceding it. Clearly I'm wrong though.

Answer

There are a lot of conditions (some repeating) and i'm not sure in what order they are supposed to be applied. My guess is that database server is having a hard time too.

You should group your conditions in cases like this. In Eloquent grouping can be implemented with anonymous functions in where() methods. If you want to apply the last condition to the whole of those preceeding it, you would do something like this:

\Lead::rightJoin("tasks", "tasks.lead_id", "=", "leads.id")
    ->where(function($q) use ($owned, $delegated)
    {
        $q->where($owned)
            ->orWhere($delegated)           
            ->where("leads.status", "!=", "Archived")
            ->where('tasks.due_date', '<', date("F j, Y", strtotime('-10 days')))
    })
    ->where("tasks.completed_at", null)
    ->get()->toArray();

Try it and adjust as needed if I didn't get the order of conditions right.