I want to get the user id and role before the user is logged in. If i have the email or username, what function can I use with D8 to get the user id ?
2 Answers
You can load the user with loadByProperties()
:
$users = \Drupal::entityTypeManager()->getStorage('user')
->loadByProperties(['mail' => $mail]);
$user = reset($users);
if ($user) {
$uid = $user->id();
$rids = $user->getRoles();
}
-
-
also the syntax is wrong on this, the mail is not closed with a ] and the double arrow shouldnt be there. can you give me the right syntax please?– DianaCommented Sep 23, 2016 at 14:17
-
2The syntax should be OK. The properties are in an array. You can place any field in this array. For the username:
['name' => $name]
or both at the same time:['name' => $name, 'mail' => $mail]
– 4uk4Commented Sep 23, 2016 at 14:58
Drupal 8 now also has these specific functions:
user_load_by_name()
$user = user_load_by_name('some user');
$uid = $user->id();
https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_load_by_name/8.9.x
user_load_by_mail()
$user = user_load_by_mail('[email protected]');
$uid = $user->id();
https://api.drupal.org/api/drupal/core!modules!user!user.module/function/user_load_by_mail/8.9.x