I've been searching for this for ages, but could not come with a solution. Drupal 7 provided a way to get the uid of a newly created user after running user_save; the new user has been added and the uid has been returned in the object. However, now in Drupal 8 when I use the User::create() method, it only returns a constant based on whether the user has been created or updated. Is there any way to get the uid after the user has been created though? I don't seem to find a way. Any help is appreciated.
Where are you creating the user? Could you use entityTypeManager and EntityStorage instead of User::create()? I have the following in a method in a custom entity:
$storage = $this->entityTypeManager()->getStorage('user'); $owner = $storage->create(['mail' => $email, 'name' => $this->getName()]); $owner->save(); $uid = $owner->id();
If you don't have access to entityTypeManager() in your class, you could alternatively use:
$storage = \Drupal::service('entity_type.manager')->getStorage('user');
To get the ID from User::create(); use the id() function after the save() function:
$user = \Drupal\user\Entity\User::create(); $user->setPassword(user_password()); $user->enforceIsNew(); $user->setEmail($user_data['user_email']); $user->setUsername($name); //Save user $res = $user->save(); //$res returns the SAVED_NEW or SAVED_UPDATED constant no good for an ID //But the id function should pass the newly created ID $newid = $user->id();