Accept array of groups for user->isInGroup() #17989
-
|
I've found myself needing to verify if a user is in any of a set of groups to access certain pages, eg: {% if currentUser.isInGroup('coachingStaff') or currentUser.isInGroup('teamAdmin') or currentUser.isInGroup('conferenceChair') %}
<!-- or the inverse -->
{% if not currentUser.isInGroup('coachingStaff') and not currentUser.isInGroup('teamAdmin') and not currentUser.isInGroup('conferenceChair') %}
{% exit 403 %}
{% endif %}I was hoping the isInGroup() function would accept an array: {% if not currentUser.isInGroup(['coachingStaff', 'teamAdmin', 'conferenceChair']) %}Our AI overlords recommended this change: /**
* Returns whether the user is in a specific group or any of the provided groups.
*
* @param int|string|UserGroup|array $group The user group model, its handle, ID — or an array of those.
* @return bool
*/
public function isInGroup(UserGroup|int|string|array $group): bool
{
if (Craft::$app->edition < CmsEdition::Pro) {
return false;
}
// Normalize to an array of group identifiers/models
$groups = is_array($group) ? $group : [$group];
foreach ($groups as $g) {
$idOrHandle = $g;
if ($g instanceof UserGroup) {
$idOrHandle = $g->id;
}
if (is_numeric($idOrHandle)) {
if (ArrayHelper::contains($this->getGroups(), fn(UserGroup $ug) => $ug->id == $idOrHandle)) {
return true;
}
} else {
if (ArrayHelper::contains($this->getGroups(), fn(UserGroup $ug) => $ug->handle === $idOrHandle)) {
return true;
}
}
}
return false;
}I realize this could bring up a potential |
Beta Was this translation helpful? Give feedback.
Answered by
brandonkelly
Oct 27, 2025
Replies: 1 comment 2 replies
-
|
Added a new |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
brandonkelly
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added a new
isInGroups()method for Craft 5.9: 1965587