Drupal 9: How delete all users from the site programmatically

4 Dec.2021
Image
drupal entities

Sometimes during development, we need to completely remove all users from the site, for example, when you copy a site for another project or work with migration.

For these purposes, we can use modules such as Entity Delete.

However sometimes more quickly just use custom code in your custom module or install devel_php and run with admin interface on /devel/php.

use Drupal\user\Entity\User;
use Drupal\user\UserInterface;
 
$ids = \Drupal::entityQuery('user')->execute();
foreach ($ids as $id) {
  $user = User::load($id);
  if ($user instanceof UserInterface && $user->id() != 0 && $user->id() != 1) {
    $user->delete();
  }
}