Skip to content
Advertisement

Laravel relationship where clause is returning records outside relationship

I have a problem where i try to get all users from Site which is defined relationship in Site model and on where clause it returns users that belong to other Site

$searchArray = ['name'];
$searchParam; //from request
$query =  Site::findOrFail($site_id)->users();


foreach($searchArray as $key => $value){
     if ($key) {
         $query->orWhere($value, 'like', '%' . $searchParam . '%');
     } else {
         $query->where($value, 'like', '%' . $searchParam . '%');
     }
}
 $query->with('someTable');
 $query->orderBy($order);
 $query->paginate(10);

Lets say that my $site_id = 2 and my $searchParam = 'Tom'. It returns Tom that belongs to Site with site_id=1 but it also returns other Tom that belongs to Site with site_id=2. What am I doing wrong here?

Advertisement

Answer

The relation query works with a ->where(), so your ->orWhere() will give results outside the relation. You can fix this by using an extra where() like this:

$searchArray = ['name'];
$searchParam; //from request
$query =  Site::findOrFail($site_id)->users();

$query->where(function($q) use ($searchArray, $searchParam) {
  foreach($searchArray as $key => $value){
     if ($key) {
         $q->orWhere($value, 'like', '%' . $searchParam . '%');
     } else {
         $q->where($value, 'like', '%' . $searchParam . '%');
     }
  }
});
 $query->with('someTable');
 $query->orderBy($order);
 $query->paginate(10); 
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement