Why I'm not able to delete all taxonomy terms tree? I'm using custom drush command for flushing my custom vocabulary:

    function drush_mm_category_delete_all() {
  $vocab = \Drupal\taxonomy\Entity\Vocabulary::load('mm_vocab');

  if (! $vocab) {
    throw new Exception("Missing 'mm_vocab' vocabulary");
  }

  $tree = \Drupal::service('entity_type.manager')
    -&gt;getStorage("taxonomy_term")
    -&gt;loadTree('mm_vocab', 0, NULL, FALSE);

  drush_print('Amount of terms to delete: ' . count($tree));
  $counter = 0;


  foreach($tree as $term) {
    $term_entity = \Drupal\taxonomy\Entity\Term::load($term-&gt;tid);
    $term_entity-&gt;delete();
    $counter++;
  }

  drush_print('Amount of deleted terms: ' . $counter);

}


I'm getting error:


  Error: Call to a member function delete() on null


but WTF? I see that loadTree returns flat array of all vocab term. It seems that all items are object with tid property.

If I add:

if ($term_entity) {
  //delete here
}


I'm able to run command without error, but only small amount of terms are deleted. Why?
The comment is correct, children are deleted automatically.

So what you can do is set the max_depth argument to 0, then you should only get the top-level terms and you can delete those.