Nana Partykar Nana Partykar - 5 months ago 70
PHP Question

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
; 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
I'm getting error like

PHP Notice – yii\base\ErrorException

Undefined offset: 0

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

$roleName = 'superadmin';


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

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


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