How to get user role in Yii2?
I searched and read Yii2 guide but I didn't find any solution.
You can get Roles for an user by using getRolesByUser function
You can use it like this
\Yii::$app->authManager->getRolesByUser($user_id);
 
    
    You can use:
Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());
 
    
     
    
    I use :
if (\Yii::$app->authManager-> getAssignment($role,$rule_id))
for filtering user id and role in rbac, More details on Yii2 Documentation
 
    
    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.
 
    
    You can use :
 $user =[];
 $userAssigned = Yii::$app->authManager->getAssignments(user_id);
 foreach($userAssigned as $userAssign){
      $user[] = $userAssign->roleName;
 } 
 
    
    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
 
    
    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
 
    
    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.
