Drupal 8 programmatically block and unblock a user

Posted on 18/09/2020

In Drupal 8/9 this is pretty straightforward as UserInterface provides two methods for doing this: block() and activate().

The only catch is that the user entity must be saved after doing this.

Code for blocking a user programmatically:

  1. /** @var \Drupal\user\UserInterface $user */
  2. $user = \Drupal\user\Entity\User::load(USER_ID_HERE);
  3. $user->block();
  4. $user->save();

Code for activating a user programmatically:

  1. /** @var \Drupal\user\UserInterface $user */
  2. $user = \Drupal\user\Entity\User::load(USER_ID_HERE);
  3. $user->activate();
  4. $user->save();