+ /**
+ * Set the assigned user roles via an array of role IDs.
+ *
+ * @throws UserUpdateException
+ */
+ public function setUserRoles(User $user, array $roles)
+ {
+ if ($this->demotingLastAdmin($user, $roles)) {
+ throw new UserUpdateException(trans('errors.role_cannot_remove_only_admin'), $user->getEditUrl());
+ }
+
+ $user->roles()->sync($roles);
+ }
+
+ /**
+ * Check if the given user is the last admin and their new roles no longer
+ * contains the admin role.
+ */
+ protected function demotingLastAdmin(User $user, array $newRoles): bool
+ {
+ if ($this->isOnlyAdmin($user)) {
+ $adminRole = Role::getSystemRole('admin');
+ if (!in_array(strval($adminRole->id), $newRoles)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+