1

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

Community
  • 1
  • 1
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77

5 Answers5

7

User can have multiple roles, and in authManager there is no method for getting just one role for user.

You can use this code in case of one role (I'd recommend to place it in a User model to keep code cleaner):

/**
 * Returns user role name according to RBAC
 * @return string
 */
public function getRoleName()
{
    $roles = Yii::$app->authManager->getRolesByUser($this->id);
    if (!$roles) {
        return null;
    }

    reset($roles);
    /* @var $role \yii\rbac\Role */
    $role = current($roles);

    return $role->name;
}

No need to check for array because getRolesByUser already returns an array.

Alternatively you can use array_shift as suggested here or return a key of array element because it's indexed by names (described here).

Because of such indexation, you can't get 0 element of an array (it simply don't exist). That's why you got Undefined offset: 0 exception.

Example of usage in view:

<?php if (!Yii::$app->user->isGuest) { ?>
    <div class="user-role"><?= Yii::$app->user->identity->getRoleName() ?></div>
<?php } ?>
Community
  • 1
  • 1
arogachev
  • 33,150
  • 7
  • 114
  • 117
  • 2
    Hi Mr Arogachev : Your code working perfectly. Thanks a lot. I was using array_shift as it is suggested by Mr @Nuriddin. But, I will use this too. Thanks :) – Nana Partykar Dec 09 '15 at 08:18
  • 1
    @NanaPartykar `array_shift` works too, please read my other remarks and explanation. – arogachev Dec 09 '15 at 08:25
3

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;
arogachev
  • 33,150
  • 7
  • 114
  • 117
  • Thanks. Nuriddin. :) – Nana Partykar Dec 09 '15 at 07:31
  • 1
    Not at all my friend. – Nuriddin Rashidov Dec 09 '15 at 07:33
  • `Yii::$app->authManager->getRolesByUser()` always returns array, so check for `is_array` is redundant. `$role` is not inappropriate name, because this array can contain more than one role, it's better to name it `$roles`. Calling `name` from `array_shift` lacks code highlighting in IDE. Code is not `PSR-2` compatible (and Yii2 follows it and recommends to follow it in your own code). – arogachev Dec 09 '15 at 08:24
1

Your array doesn't have the 0 index. As the documentation says the array is indexed by the role names.

So, if you have 100% all users will always have only one role. You could call it like this:

print_r(reset($Role));

But if the user can have multiple roles, you can use a loop for that:

foreach ($Role as $each) {
    print_r($each);
}
Clyff
  • 4,046
  • 2
  • 17
  • 32
  • User has one role only. And, when i do `print_r(reset($Role));` I get `yii\rbac\Role Object ( [type] => 1 [name] => superadmin [description] => Super admin can do any operation in the application [ruleName] => [data] => [createdAt] => [updatedAt] => ) `. And, when i do like `print_r(reset($Role['name']));` or `print_r(reset($Role->name));` . I get error like **Attempt to modify property of non-object** Please suggest me how to take `name`. Thanks – Nana Partykar Dec 09 '15 at 07:22
  • Yup you used wrongly. Since `reset` was returning your object, it was just a matter of calling any attribute of it AFTER the reset. It would be `print_r(reset($Role)->name)`. Too bad you din't noticed (or even asked me) that before, i was the first to answer T-T – Clyff Dec 09 '15 at 12:57
  • Sorry Mr @Clyff. Please Don't Mind. Thanks For Your Effort. I'm Embarassaed. – Nana Partykar Dec 09 '15 at 13:27
  • 1
    Hahaha ok nevermind, it happens. But i would recommend you use my suggestion in your project, is the fastest / cleanest. – Clyff Dec 09 '15 at 13:35
1
$getRolesByUser = Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());

$Role = array_keys($getRolesByUser)[0];
Bugs
  • 4,491
  • 9
  • 32
  • 41
xPeng
  • 21
  • 5
0

in my opinion the best way is:

if (array_key_exists('Admin', \Yii::$app->authManager->getRolesByUser(Yii::$app->user->id))) { ... }

PS the above for the Role "Admin".