How can I programmatically deactivate multiple user accounts? I have tried the following code, but something doesn't work, could you please help. I need to deactivate several accounts at once, if they satisfy the conditions: 

$ids = \Drupal::entityQuery('user')
  -&gt;condition('roles', 'student')
  -&gt;condition('field_school_id', $node_id)
  -&gt;execute();
$users = User::loadMultiple($ids);


$storage_handler = \Drupal::entityTypeManager()-&gt;getStorage("user");

foreach($users as $user){
  $entity = $storage_handler-&gt;load($user-&gt;id());
  $entity-&gt;set("status", 0);
  $storage_handler-&gt;save($entity); // THE PROBLEM IS IN THIS LINE
}
The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in $user.

Change your foreach loop to look like this and it should work:

foreach ($users as $user) {
  $user-&gt;set("status", 0);
  $user-&gt;save();
}


You can also remove the $storageHandler since you don't use that any more.