Drupal 8: Taxonomy Terms by Level

In Drupal 8, sometimes we have a lot of levels of taxonomy terms and we need to manage this in our code. For example, what if we need to get a specific level of the taxonomy?

So let’s imagine the following taxonomy tree:

  • Drinks
    • Alcohol Drinks
      • Beer
      • Whiskey
      • Vodka
    • Alcohol Free Drinks
      • Coca Cola
      • Pepsi
      • Milk
  • Fruits
    • Fruits For Losing Weight
      • Apricot
      • Blackberrie
      • Cantaloupe
    • Fruits For Dogs
      • Strawberry
      • Watermelon
      • Orange
  • Foods
    • Fast Foods
      • Hamburger
      • Pizza
      • Hot Dog
    • Healthy Foods
      • Almond
      • Oily Fish
      • Avocado

Below is a method to get only the 1st level:

Get the 1st and 2nd levels:

Get only the 2nd level:

Get the 2nd and 3rd levels:

Get only the last level:

I would like add a note about using the entity type manager service.  Actually, this applies to all Drupal services… In the above examples we got this service by static method via a Drupal object:

But the better way to get this service is to use Dependency Injection.