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.
You're looking for the
whereHas()
method:->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 onlyUser
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).