Josh Kirkpatrick
Josh Kirkpatrick

Reputation: 403

applying a where to users relation

i have this line

return User::with('image')->with('profile')->paginate(30);

which grabs all the users with there image data and profile data, however i cant seem to find a way to apply a where clause to the profile

for instance if i wan't to get all the users, with there image and profile but only if a value in there profile is equal to x so for example if gender is set to male in there profile i wan't to grab them

how can i do this without grabbing everybody regardless of what a value is in the profile relation?

Upvotes: 0

Views: 26

Answers (1)

Josh Forbes
Josh Forbes

Reputation: 328

You can use the whereHas method:

return User::with('image', 'profile')->whereHas('profile', function ($query) {
    $query->where('gender', 'male');
})->get();

Upvotes: 1

Related Questions