Search code examples
phpyii2yii2-advanced-appyii2-basic-appyii2-user-roles

To Get Role Of A User - Yii2


I was searching for user role for logged in user, I'm not getting how to print user role name. I Tried this:

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

When, I did print_r($Role); I got this :

Array ( [superadmin] => yii\rbac\Role Object ( [type] => 1 [name] => superadmin [description] => Super admin can do any operation in the application [ruleName] => [data] => [createdAt] => [updatedAt] => ) )

I was looking to get particular role name, but i was unable to access

Array ( [superadmin] => yii\rbac\Role Object ........)
           ^ unable to access this name.

When typing print_r($Role[0]->name); I'm getting error like

PHP Notice – yii\base\ErrorException

Undefined offset: 0

And, If I do like this way (means, manually passing $rolename to array index) It is working.

$roleName = 'superadmin';

print_r($Role[$roleName]->name);

Why this requirement came to me, because for logged in user It's Ok. But, if i want to know other user role name, then I need that index name to pass here $Role[$roleName]->name

Please help me to access this 'superadmin'. I'm not getting how to get index name of it.

Array ( [superadmin] => yii\rbac\Role Object
               ^ unable to access this name.

I also checked Get User Role & Specific Role Of User


Solution

  • So you can use for this array_shift. It's return first element of array E.g:

    if(is_array($Role))array_shift($Role)->name;