Hide a view programatically D8
I assume your view is using a block display and you don't want the block to display at all if there is only 1 result.

In my opinion you are hooking in too late in the process to hide the view there. It is possible to hide it in the theme layer but I don't think it is the optimal approach.

There are a number of ways you can do it but here are a couple of ways using a hook in a custom module, not in a theme. (This is not an exhaustive list of options that you have.)

Option 1


Hook into the view execution process and tell the process that execution has failed, so it will not render the view.


For example:

use Drupal\views\ViewExecutable;

function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // If there is only 1 result set the failure condition so that
  // execution will not continue and the view will not display.
  if ($view-&gt;id() == 'VIEW_NAME') {
    if (count($view-&gt;result) == 1) {
      $view-&gt;build_info['fail'] = TRUE;
    }
  }
}


Option 2


Configure your view to have 'Hide block if the view output is empty' = Yes
Hook into the view execution process and clear the results when you don't want it to display.


For example:

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_post_execute().
 */
function MODULE_NAME_views_post_execute(ViewExecutable $view) {
  // Clear the results if there is only 1 result.
  // The view will then hide as it is configured to hide the
  // block if empty.
  if ($view-&gt;id() == 'VIEW_NAME') {
    if (count($view-&gt;result) == 1) {
      $view-&gt;result = array();
    }
  }
}


Note: Depending on how you decide to hide the view, if your views block is the only block in your region then be aware of this outstanding bug, which may cause your region to still display even though your block doesn't: https://www.drupal.org/project/drupal/issues/953034