b24
b24

Reputation: 2473

How to get user role in Yii2?

How to get user role in Yii2?

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

Upvotes: 19

Views: 46283

Answers (8)

Alliswell
Alliswell

Reputation: 1583

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

Upvotes: 0

Imtiaz
Imtiaz

Reputation: 2534

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

Upvotes: 0

Awais Mustafa
Awais Mustafa

Reputation: 151

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.

Upvotes: -2

Mohan Prasad
Mohan Prasad

Reputation: 682

You can use :

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

Upvotes: 1

Denis Solovyov
Denis Solovyov

Reputation: 19

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.

Upvotes: 1

elfarqy
elfarqy

Reputation: 171

I use :

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

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

Upvotes: 10

d4v1d
d4v1d

Reputation: 351

You can use:

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

Upvotes: 21

Manquer
Manquer

Reputation: 7647

You can get Roles for an user by using getRolesByUser function

You can use it like this

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

Upvotes: 38

Related Questions