How to check whether a username already exists? I had created a controller where I can create a new user programmitically by the following code. 

$user = User::create();

      //Mandatory settings
      $user-&gt;setPassword($password);
      $user-&gt;enforceIsNew();
      $user-&gt;setEmail($email);

      //This username must be unique and accept only a-Z,0-9, - _ @ .
      $user-&gt;setUsername($username);

      //Optional settings
      $language = 'en';
      $user-&gt;set("init", 'email');
      $user-&gt;set("langcode", $language);
      $user-&gt;set("preferred_langcode", $language);
      $user-&gt;set("preferred_admin_langcode", $language);
      $user-&gt;activate();

      //Save user
      $user-&gt;save();
      drupal_set_message("User with uid " . $user-&gt;id() . " saved!\n");

      $uid = $user-&gt;id();


I am passing all variables via postman by POST method. I am using email as the username. But I want to check a condition (whether the username is already exist ) before the user creation. How can I write the if condition?
I guess you can use a simple EntityQuery.

  $ids = \Drupal::entityQuery('user')
        -&gt;condition('name', 'USERNAME_TO_CHECK')
        -&gt;range(0, 1)
        -&gt;execute();
    if(!empty($ids)){
      //then this name already exists
    }