Laravel Query Where Relationship within Relationship Condition

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Laravel Query Where Relationship within Relationship Condition on this date .

Been trying to resolve this query for a long time now, it’s working but there is a bit of misquery.

This is one of my queries from my search function with livewire.

return empty($search)
    ? static::query()  
    : static::query()->where('id','like','%'.$search.'%')
        ->orWhereHas('status.user',function($q) use ($search){
            $q->where('active',1)
                ->where('name','like','%'.$search.'%')
                ->orWhere('username','like','%'.$search.'%');
        });

For example, I type the name of ‘jason’ the query will return the correct result, but if I type Jason’s username it will return every record that Jason’s been update (but not active) I just want the action to return with a particular name or username.

I already try to separate the active, name, and username on different functions but the result is the same.

Answer

AND has precedence over OR so this condition

$q->where('active',1)
  ->where('name','like','%'.$search.'%')
  ->orWhere('username','like','%'.$search.'%');

is evaluating like – where ( active = 1 and name like '%$search%' ) or username like '%$search%'

But if I am not wrong then your want something like where active = 1 and ( name like '%$search%' or username like '%$search%')

To achieve this you can try segregating above condition like –

 $q->where('active',1)
   ->where(function($q2) use ($search){
         $q2->where('name','like','%'.$search.'%')
         $q2->orWhere('username','like','%'.$search.'%');
 });

Please let me know if it worked.