5

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 ?

12

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();
}
  • thanks what about the user name? – Diana Sep 23 '16 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 '16 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] – 4k4 Sep 23 '16 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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