How to get user role in Yii2?

2020-02-25 08:12发布

How to get user role in Yii2?

I searched and read Yii2 guide but I didn't find any solution.

标签: php yii yii2 rbac
8条回答
We Are One
2楼-- · 2020-02-25 08:17

You can get Roles for an user by using getRolesByUser function

You can use it like this

\Yii::$app->authManager->getRolesByUser($user_id);
查看更多
放我归山
3楼-- · 2020-02-25 08:28

You can use :

 $user =[];
 $userAssigned = Yii::$app->authManager->getAssignments(user_id);
 foreach($userAssigned as $userAssign){
      $user[] = $userAssign->roleName;
 } 
查看更多
Evening l夕情丶
4楼-- · 2020-02-25 08:28

The good and more visual decision will be setting constants of all roles.

$userID = $user->getId();
array_keys(Yii::$app->authManager->getRolesByUser($userID))[0] == User::ROLE_NAME
查看更多
手持菜刀,她持情操
5楼-- · 2020-02-25 08:30

You can use:

Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
查看更多
虎瘦雄心在
6楼-- · 2020-02-25 08:32

One more example how to get user role:
Yii::$app->getUser()->identity->role;
It works if you have column with name "role" in your user table.

查看更多
家丑人穷心不美
7楼-- · 2020-02-25 08:35

If you're using amnah/yii2-user module, you can use this:

Yii::$app->user->identity->role->name

It will give you the current user role name

查看更多
登录 后发表回答