+ /**
+ * Set the assigned user roles via an array of role IDs.
+ * @param User $user
+ * @param array $roles
+ * @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.
+ * @param User $user
+ * @param array $newRoles
+ * @return bool
+ */
+ protected function demotingLastAdmin(User $user, array $newRoles) : bool
+ {
+ if ($this->isOnlyAdmin($user)) {
+ $adminRole = $this->role->getSystemRole('admin');
+ if (!in_array(strval($adminRole->id), $newRoles)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+