how to create user in drupal 8 code example

Example 1: drupal 8 get user

$current_user = \Drupal::currentUser();
$user = \Drupal\user\Entity\User::load($current_user->id());

// or just
$user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

Example 2: drupal create user

$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
$user = \Drupal\user\Entity\User::create();

//Mandatory settings
$user->setPassword('test');
$user->enforceIsNew();
$user->setEmail('[email protected]');
$user->setUsername('test'); //This username must be unique and accept only a-Z,0-9, - _ @ .

//Optional settings
$user->set("init", 'email');
$user->set("langcode", $language);
$user->set("preferred_langcode", $language);
$user->set("preferred_admin_langcode", $language);
//$user->set("setting_name", 'setting_value');
$user->activate();

//Save user
$user->save();

Tags:

Php Example