I need to get the group code of the current user in backend, how can I do this?
Asked
Active
Viewed 986 times
0
-
The current user might be member of multiple groups. Check the following link, it may give you a clue: https://stackoverflow.com/a/47875582/69537 – B Faley Dec 19 '17 at 03:05
2 Answers
2
Shorter version of Hardik Satasiya code
$user = \BackendAuth::getUser();
$userGroupCodes = $user->getGroups()->lists('code');
$neededCode = 'owners';
$hasPermission = in_array($neededCode, $userGroupCodes);

Edgars Ozolins
- 298
- 5
- 11
1
I guess you need to check weather user is inside of group or not and based on you need to enforce some security/rights etc..
here is the code which can be useful.
user can have multiple
usergroup
so you will get multipleusergroup-code
then you can check from it. (in this example we are checking user hasowners
code in his groups)
$user = \BackendAuth::getUser();
$currentUserGroups = $user->getGroups();
$userGroupCodes = [];
$neededCode = 'owners';
foreach ($currentUserGroups as $group) {
$userGroupCodes[] = $group->code;
}
$hasPermission = false;
if(in_array($neededCode, $userGroupCodes)) {
$hasPermission = true;
}
dd($hasPermission);
$hasPermission will have the Boolean value now you can use it in your condition and enforce security.

Hardik Satasiya
- 9,547
- 3
- 22
- 40
-
I need user group for display records in my plugin. I use this in my plugin.php boot function, and i have Error: - Call to a member function getGroups() on null – Elisseii Dec 19 '17 at 11:09
-
you need to wrap it inside some relevant event or something else because during boot Backed user is not initialized. – Hardik Satasiya Dec 19 '17 at 11:15
-
I created another question, you can try to answer it. I will be very happy)) https://stackoverflow.com/q/47888265/8221154 – Elisseii Dec 19 '17 at 13:44