Error when trying to load taxonomy term name from tid I am trying to replace a view name with the name of a taxonomy term that is determined from a url argument. 

When I explicitly set $tid, the following works flawlessly:

function hook_views_pre_render(ViewExecutable $view) {
  $tid = 2;
  $term = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load($tid);
  $name = $term-&gt;label();
  $view-&gt;setTitle($name);
}


However, if $tid is determined from my argument, as in:

function hook_views_pre_render(ViewExecutable $view) {
  $tid = $view-&gt;args[0];
  // or alternatively $tid = intval($view-&gt;args[0]);
  $term = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load($tid);
  $name = $term-&gt;label();
  $view-&gt;setTitle($name);
}


...then I get the following error:

The website encountered an unexpected error. Please try again later.
Error: Call to a member function label() on null in hook_views_pre_render() 


...on the line containing $name = $term-&gt;label().

I am at a loss as to why this is happening. When I inspect kint($term) in either situation, all of the data for the loaded term appears to be available. I've also verified that:

if   $tid1 = 2;
and  $tid2 = intval($view-&gt;args[0]);
then $tid1 === $tid2
Because there is the case when no argument is passed and $tid is null. So better keep a check you have data in variable $tid and further perform the task. Even the view name condition is not mentioned so it may apply to all views.

  function hook_views_pre_render(ViewExecutable $view) {
      $tid = $view-&gt;args[0];
      // or alternatively $tid = intval($view-&gt;args[0]);
    if(isset($tid) &amp;&amp; !empty($tid)){
      $term = \Drupal::entityTypeManager()-&gt;getStorage('taxonomy_term')-&gt;load($tid);
      $name = $term-&gt;label();
      $view-&gt;setTitle($name);
    }
    }