Home > database >  Check user roles using two tables
Check user roles using two tables

Time:11-09

I want to display users with a specific role. I have three tables.

user_roles table

role_id User_id
1 1
1 1
3 2

roles table

id name
1 chair
2 doctor

users table

id name
1 test
2 user

The roles table have a foreign key with role_id in user_roles table.

I want to fetch users in user table where role = doctor.

I have two models

User model Roles model

`

 public function showDoctor ()
    {
         $users = User::all();

        <-- I want to return the code here to for the users -->
        
        return $users;
    }

`

CodePudding user response:

define the relation between users and roles in User model

function Roles(){
   return $this->belongsToMany(Role:class);
}

and you can have your condition like this

User::whereHas('Roles' , function($role){

  $role->where('name' , 'doctor');

});
  • Related