简体   繁体   English

如何根据用户在Laravel 5中的角色选择用户?

[英]How to select users based on the role that they have in Laravel 5?

From my controller I would like to select all of the users that have the role "client". 从我的控制器我想选择所有具有“客户端”角色的用户。

I have a User model and a Role model. 我有一个用户模型和一个角色模型。 A role belongs to many users and a user belongs to many roles. 角色属于许多用户,用户属于许多角色。

I've established my models and have some helper functions at the model instance level for fetching roles and users 我已经建立了我的模型,并在模型实例级别有一些辅助函数来获取角色和用户

Here are the User and Role database models: 以下是用户和角色数据库模型:

app/User.php 应用程序/ user.php的

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    // User belongs to many roles
    public function roles()
    {
        return $this->belongsToMany('App\Role')->withTimestamps();
    }

    // whitelist specific roles
    // reject if user does not have given roles
    public function authorizeRoles($roles)
    {
        if ($this->hasAnyRole($roles)) {
            return true;
        }

        abort(401, 'This action is unauthorized.');
    }

    // Check if a user has a role
    public function hasRole($role)
    {
      if ($this->roles()->where('name', $role)->first())
      {
        return true;
      }

      return false;
    }

    // Pass in string or array to check if the user has a role
    public function hasAnyRole($roles)
    {
      if (is_array($roles)) {
        foreach ($roles as $role) {
          if ($this->hasRole($role)) {
            return true;
          }
        }
      } else {
        if ($this->hasRole($roles)) {
          return true;
        }
      }
      return false;
    }
}

app/Role.php: 应用程序/ Role.php:

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany('App\User')->withTimestamps();
    }
}

I have migrations for a create_users_table , create_roles_table and a pivot table for create_role_user_table . 我有create_users_tablecreate_roles_tablecreate_role_user_table的数据透视表的迁移 Each role has an id, name and description. 每个角色都有一个id,名称和描述。 Each user has an id, name, email and password. 每个用户都有一个ID,名称,电子邮件和密码。

I would like to filter by all users that have the role called "client". 我想过滤所有具有“客户端”角色的用户。

In my controller method I try to call roles but it does not work because it is an instance method: 在我的控制器方法中,我尝试调用角色,但它不起作用,因为它是一个实例方法:

// Display admin dashboard
public function admin(Request $request)
{
    // check to make sure user is an admin
    $request->user()->authorizeRoles('admin');

    // Display all users that have the role "client"
    // ***** section that does not work ********
    $users = User::all()->roles()->where('name', 'client')->get();

    return view('admin', compact('users'));

}

How can I populate the $users variable with only users who have the role with name "client"? 如何只使用名为“client”的角色的用户填充$users变量?

Use whereHas() method: 使用whereHas()方法:

User::whereHas('roles', function ($q) use ($roleName) {
    $q->where('name', $roleName);
})->get();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM