Create users programmatically and adding roles

Drupal 8 :

 

Create an user and add roles to it programmatically

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



// The Basics
$user->setUsername('monkpal');  // You could also just set this to "monkpal" or something...
$user->setPassword('monkpal');
$user->setEmail('mailid');
$user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object

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

//Add role 

$user->addRole("somerolename");

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