I am trying to check if the email provided by a user using a custom webform is already associated with an account on my site. In the case it's used, I want to get the roles of the account using that email.

I am using the following code.

$email = "[email protected]";

// Loads existing Drupal user object by given email.
// Note that first matching user is returned. Email address and account name
// are unique so there can be only 'zero' or 'one' matching user when
// loading users by these properties.

// Load entities by other than entity ID.
$users = \Drupal::entityTypeManager()
  ->loadByProperties(['mail' => $email]);

// if 'One' user has been found matching the given email.
if (!empty($users)) {

    // Set the disabled roles.
    $disabled_roles = array ("administrator", "content_approver");

    // Loop through all roles the user has.
    // The following is the line causing the error (line 74).
    foreach ($users->getRoles() as $role) {
        // Check if the user has one or more disabled role.
        if (array_key_exists($role, $disabled_roles)) {

           // Extra codes goes here.


I get the following error.

Error: Call to a member function getRoles() on array in Drupal\custom_module\Controller\EmailCheckController->EmailCheck() (line 74 of /home/users/public_html/example.com/web/modules/custom/custom_module/src/Controller/EmailCheckController.php)

What is wrong with my code? How can I get the roles of the user accounts I load?


1 Answer 1


EntityStorageInterface::loadByProperties() returns an array of objects, and it returns an array regardless of the number of results. Even if you have one result (which I am guessing is what you're expecting) you get an array back.

You can't call getRoles() on an array. You'll need to get the objects from the array before you do that. For example, on EntityStorageBase::loadByProperties a commenter uses $first_match = reset($entities);.


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.