How to get user role in Yii2?

2020-02-25 08:33发布

问题:

How to get user role in Yii2?

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

回答1:

You can get Roles for an user by using getRolesByUser function

You can use it like this

\Yii::$app->authManager->getRolesByUser($user_id);


回答2:

You can use:

Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());


回答3:

I use :

if (\Yii::$app->authManager-> getAssignment($role,$rule_id))

for filtering user id and role in rbac, More details on Yii2 Documentation



回答4:

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.



回答5:

You can use :

 $user =[];
 $userAssigned = Yii::$app->authManager->getAssignments(user_id);
 foreach($userAssigned as $userAssign){
      $user[] = $userAssign->roleName;
 } 


回答6:

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



回答7:

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


回答8:

You can get role of the user by using createcommand.

    $roleModel = Yii::$app->db
    ->createCommand("Select * from auth_assignment where user_id='889'")
    ->queryOne();

    echo $roleModel['item_name'];

This will you user's role in auth assignment. Now you can check that if user is admin or editor or member.



标签: php yii yii2 rbac