Yii2: authManager should have a method like userHasRole()

Sometime I just want to know if a user has a certain role or not. Especially for the current authenticated user.

One can use Yii::$app->authManager->getRolesByUser($user_id) to get the roles and then loop through them to find out if the user has got the role. But it could already part of the BaseManager (abstract or base implementation, and finally implemented in PhpManager and DbManager) with a method like userHasRole($user_id, $role) which returns true or false.

Even better would be Yii::$app->user->hasRole($role). Is this possible?

This could result in better performance - e.g. the DbManager could use better queries.

Yes, it’s just


1 Like

Okay, this already exists. Though, in my opionion ‘can’ is a not so obvious method name in context of roles.

Yeah but checking for role and not specific permission isn’t common either.

Ah, I see. Thanks for you hint. I’m not that experienced with RBAC. I thought it would be okay, but most likely you’re right.

Is this documented in the Yii Guide or anywhere else? Do you have a link? I think the Yii Guide just says that you can use roles and permissions but does not suggest how to do it or what is best practice.