I am trying to get users from users table. I have another table user_details which stores custom profile fields. The user_details table has four columns id,user,user_register_field,value.
id user user_register_field value 1 1 gender Male 2 1 city somecity 3 1 country somecountry 4 2 gender Female 5 2 city Null 6 2 country somecountry 7 3 gender Male
Users.php
public function Udetails()
{
return $this->hasMany('App\UserDetails','user');
}
Suppose user with user id 1 logged in & I want to show him the another users from same Country & City from which the user 1 is from.
just do something like this:
User::whereHas('Udetails',function($q){
$q->where('user_register_field','country')
->where('value',your_logged_users_country);
})->whereHas('Udetails',function($q){
$q->where('user_register_field','city')
->where('value',your_logged_users_city);
})->get();
I guess you need some sort of Parameter Grouping
criteria
User::whereHas('Udetails',function($query) use ($country, $city){
$query->where(function ($query) {
$query->where('user_register_field', '=', 'country')
->where('value', '=', $country);
})->orWwhere(function ($query) {
$query->where('user_register_field', '=', 'city')
->where('value', '=', $city);
});
})->get();