How to find, get taxonomy term by name and vocabulary in Drupal 8.

You need to get a taxonomy term id by name in Drupal 8. Useful for migrations.
<?php

 
/**
   * Utility: find term by name and vid.
   * @param null $name
   *  Term name
   * @param null $vid
   *  Term vid
   * @return int
   *  Term id or 0 if none.
   */
 
protected function getTidByName($name = NULL, $vid = NULL) {
   
$properties = [];
    if (!empty(
$name)) {
     
$properties['name'] = $name;
    }
    if (!empty(
$vid)) {
     
$properties['vid'] = $vid;
    }
   
$terms = \Drupal::entityManager()->getStorage('taxonomy_term')->loadByProperties($properties);
   
$term = reset($terms);

    return !empty(
$term) ? $term->id() : 0;
  }

?>
Tags