如何在Laravel5.2中找到当前用户的角色?

时间:2016-02-28 05:13:21

标签: php laravel roles

我在Laravel 5.2中使用包“romanbican / roles”,
如何找到当前用户的角色?

控制器:

public function index()
{
    $user = \Auth::user();
    $name=$user->name;
    $role = Role::find(......);   //How to find the  role  of current user ?
    return view('index', compact('name','role'));
}

eidt-1:

控制器:

public function index()
    {
        $user = \Auth::user();
        $name=$user->name;
        $role = $user->getRoles();
      //  return view('index', compact('name','role'));
        dd($role);
    }

edit-1的结果:

Collection {#370 ▼
  #items: []
}

它是空的,为什么? @Mahfuz

用户:

class User extends Model implements AuthenticatableContract, CanResetPasswordContract, HasRoleAndPermissionContract

{
    use Authenticatable, CanResetPassword, HasRoleAndPermission;

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

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

}

1 个答案:

答案 0 :(得分:0)

首先在用户模型中包含HasRoleAndPermission Trait

然后你可以使用这个方法

$user->getRoles()

它会回来 将所有角色用作集合。