Using where based on relationships with Laravel

73 Views Asked by At

I'm trying to filter users based on with() relationship. By filter, I mean do not return that user at all.

User::with('info');

This works for returning the "info" relationship.


Now I want to query based on.

  • where('info.allowance', null);

If I try this:

User::with(['info' => function($q) {
   return $q->where('allowance', '>', 0);
})

... it returns all the users but only the "info" model for the users that has allowance > 0. This is not what I want.

What I want: return only the users that has allowance > 0.

1

There are 1 best solutions below

2
On BEST ANSWER

You're looking for the whereHas() method:

User::with(['info' => function($q) {
  return $q->where('allowance', '>', 0);
})->whereHas('info', function($q) {
  return $q->where('allowance', '>', 0);
})->get();

->with() is for eager-loading, so each instance of $user->info will be constrained to the logic passed, but ->whereHas() constrains the original query, so it'll return only User records that match the given logic.

Sidenote, it looks odd that you use the same clause for both, but you can (and in this case should).