Populate Taxonomy Term reference field in node I'm using data from JSON to create new nodes on my Drupal 8 website. So, I have a createNode method that create these nodes.

Here is the code I'm using

  protected function createNode($json) {

    foreach ($json as $row) {
      $node = Node::create(array(
        'type' =&gt; 'product',
        'langcode' =&gt; 'en',
        'uid' =&gt; '1',
        'status' =&gt; 1,
        'title' =&gt; $row['title'],
        'field_code' =&gt; $row['code'],
        'field_manufacture' =&gt; $row['manufacture'],
        'field_product_type' =&gt; $row['type'],
        'field_barcode' =&gt; $row['barcode'],
        'field_packages' =&gt; $row['packages'],
        'field_pallet' =&gt; $row['pallet'],
      ));

      $node-&gt;save();
    }

  }


The problem is with field_manufacture and field_product_type, those are entity reference field to taxonomy term. I'm getting term name and I need to match it in vocabulary or add it if doesn't exist.

Any idea how to do that?
First, find the taxonomy term id by the term name as given below.  

function getTidByName($name = NULL, $vocab_name = NULL) {
  $properties = [];
  if (!empty($name)) {
    $properties['name'] = $name;
  }
  if (!empty($vocab_name)) {
    $properties['vid'] = getVidByName($vocab_name);
  }
  $terms = \Drupal::entityTypeManager()
    -&gt;getStorage('taxonomy_term')
    -&gt;loadByProperties($properties);
  $term = reset($terms);
  return !empty($term) ? $term-&gt;id() : 0;
}


Above function will return the term id and then pass this term id to your field like 

// Assigning the entity reference value.
if ($tid &gt; 0) {
  $entity-&gt;set('field_example', ['target_id' =&gt; $tid]);
}