6

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 2

14

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();
}
3
  • thanks what about the user name?
    – Diana
    Sep 23, 2016 at 14:07
  • 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?
    – Diana
    Sep 23, 2016 at 14:17
  • 2
    The 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]
    – 4uk4
    Sep 23, 2016 at 14:58
5

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.