Home > other >  Multiple whereHas Laravel eloquent query
Multiple whereHas Laravel eloquent query

Time:11-11

Please help me to simplify Laravel eloquent query. Is there a way to make it more simple, please suggest because I have a couple of these in my code or suggest me any strategy to make it simpler?

if (!empty($has_due_date)){
        $resourceQuery->whereHas('stages', function ($query) use ($has_due_date) {
            $query->whereHas('groups', function ($query) use ($has_due_date) {
                $query->whereHas('tasks', function ($query) use ($has_due_date){
                    if ($has_duedate == 'yes'){
                        $query->whereNotNull('due_date');
                    }else if($has_duedate == 'no'){
                        $query->whereNull('due_date');
                    }
                });
            });
        });
    }

CodePudding user response:

The method whereNull has a third parameter not, so it could be just like this:

$resourceQuery->when($has_due_date, function ($query, $hasDueDate) {
    return $query->whereHas('stages.groups.tasks', function ($query) use ($hasDueDate) {
        $query->whereNull('due_date', 'and', $hasDueDate === 'yes');
    });
});

Intead of if use conditional clause.

And don't forget you may use "dot" notation to execute a query against a nested relationship, more info here.

CodePudding user response:

Maybe this:

        $resourceQuery->when(!empty($has_due_date), function ($q1) use ($has_due_date){
             $q1->whereHas('stages.groups.tasks', function ($q2) use ($has_due_date) {
                    if ($has_due_date == 'yes'){
                        $q2->whereNotNull('due_date');
                    }else{
                        $q2->whereNull('due_date');
                    }
              });
        });
  • Related