4 Dec.2021

Drupal 9: How delete all users from the site programmatically

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')
  ->accessCheck(FALSE)
  ->execute();
foreach ($ids as $id) {
  $user = User::load($id);
  if ($user instanceof UserInterface && $user->id() != 0 && $user->id() != 1) {
    $user->delete();
  }
}

Ruslan Piskarov

Ukraine
PHP/WEB Developer / Drupal Expert. More than 11 years of experience delivering Drupal based General Purpose solutions for different sectors such as Job Boards, Product Portfolios, Geo Coding, Real Estate solutions, E-Commerce, Classifieds, Corporate and online Magazines/Newspapers.

Versions