How to programmatically create a user in Drupal 8

Make user account programmatically with PHP in Drupal 8
Make user account programmatically with PHP in Drupal 8

No more user_save() and such. What is a nerd to do?

Try the following code, and for those of you programmatically migrating users across from an old site, note that you can set the new user's ID to whatever you want! You don't have to let the system auto-assign the next-available number according to the database. And when you go back to creating users "the normal way" it will resume with the next number after the highest you've assigned. Pretty cool!

$guy = $x->fetch();
 
    $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
    $user = \Drupal\user\Entity\User::create();
 
// Optional line:  Do this if you want to pick the user's ID !!!
    $user->uid = $old_user_account_from_your_other_system['uid'];  // Or 42, etc - or just omit it and let it be auto-assigned if you don't care
 
// The Basics
    $user->setUsername($old_user_account_from_your_other_system['uid'];  // You could also just set this to "Bob" or something...
    $user->setPassword('Bosco');
    $user->setEmail('Yourmail@123.corp');
    $user->enforceIsNew();  // Set this to FALSE if you want to edit (resave) an existing user object
 
// Optional settings  <-- Thanks to http://drupal8.ovh/ for these suggestions!
    $user->set("init", 'Yourmail@123.corp');
    $user->set("langcode", $lang);
    $user->set("preferred_langcode", $lang);
    $user->set("preferred_admin_langcode", $lang);
    //$user->set("setting_name", 'setting_value');
    $user->activate();
 
// Save user
    $result = $user->save();

Tags: