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

从我的控制器我想选择所有具有“客户端”角色的用户.

我有一个用户模型和一个角色模型.角色属于许多用户,用户属于许多角色.

我已经建立了我的模型,并在模型实例级别有一些辅助函数获取角色和用户

以下是用户和角色数据库模型:

应用程序/ 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;
    }
}

应用程序/ Role.PHP

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

我有create_users_table,create_roles_table和create_role_user_table的数据透视表的迁移.每个角色都有一个id,名称和描述.每个用户都有一个ID,名称,电子邮件和密码.

我想过滤所有具有“客户端”角色的用户.

在我的控制器方法中,我尝试调用角色,但它不起作用,因为它是一个实例方法

// 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'));

}

如何只使用名为“client”的角色的用户填充$users变量?

解决方法:

使用whereHas()方法

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

相关文章

统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...
前言 之前做了微信登录,所以总结一下微信授权登录并获取用户...
FastAdmin是我第一个接触的后台管理系统框架。FastAdmin是一...
之前公司需要一个内部的通讯软件,就叫我做一个。通讯软件嘛...
统一支付是JSAPI/NATIVE/APP各种支付场景下生成支付订单,返...