In Drupal 8, when I use User::create()
, it only returns a constant based on whether the user has been created or updated.
To make it clearer to the users who will read this question: User::create()
returns the created user entity. It cannot return a value that says whether the user object has been created or updated, as User::create()
doesn't save the user object in the database, nor does it check there is a duplicated user object in the database.
It's User::save()
that returns that value, but that isn't an issue, thought, since the value returned from User::create()
should be stored in a variable. The following code is wrong code to use to create a new user entity.
User::create(['mail' => $email, 'name' => $name])->save();
The call to save()
should not be concatenated to the call to create()
when the code also needs to access the properties of the created user entity, such as its ID. To achieve that, the code should be similar to the following one.
$user = User::create(['mail' => $email, 'name' => $name]);
$user->save();
Alternatively, the following code is equivalent.
$entity_type_manager = \Drupal::entityTypeManager();
$storage = $entity_type_manager->getStorage('user');
$user = $storage->create(['mail' => $email, 'name' => $name]);
$user->save();
Is there any way to get the user ID after the user has been created?
After calling $user->save()
, the user ID is returned from $user->id()
.