I've User, UserPhoto and UserProfile models.
User model have two relations profile and photos
//Relation to user_profiles table
public function profile()
{
return $this->belongsTo(UserProfile::class, 'id', 'user_id');
}
//Relation to user_photos table
public function photos()
{
return $this->hasMany(UserPhoto::class, 'user_id', 'id');
}
I wrote like this:
$users = User::whereHas('photos')
->where(['role_id' => $roleId, 'status' => User::STATUS_APPROVED]);
if (!empty($request->input('gender')))
{
$gender = $request->gender;
$users->whereHas('profile', function ($query) use ($roleId, $gender) {
$query->where('gender', '=', $gender);
});
$users->orWhereHas('profile', function ($query) use ($roleId, $gender) {
$query->where('interested_in', '=', $roleId)
->where('gender', '=', $gender);
})->whereHas('photos');
}
if (empty($request->all()))
{
$users->orWhereHas('profile', function ($query) use ($roleId) {
$query->where('interested_in', '=', $roleId);
})->whereHas('photos');
}
$users = $users->paginate(6);
users table has fields
id, name, role_id, status, ....
user_profiles table has fields
id, user_id,gender,location,state,country,interested_in,...
user_photos table has fields
id, user_id, image, is_featured,...
For example, I want to get all users with role_id = 2 or interested_in = 2 and gender = 2 and status = 2.