8

In magento 1.9, I used loadByEmail method from resource model.

But in magento2 in Magento\Customer\Model I see loadByEmail method. Customer factory, as well as customer entity which I get from quote, returns Magento\Customer\Model\Data\Customer which does not have this method.

Also CustomerRepository have only getById method.

how to load customer entity by email ?

2 Answers 2

22

In Magento 2 you need to use the get method from the Magento\Customer\Api\CustomerRepositoryInterface service contract class.

public function get($email, $websiteId = null);
5
  • What is this get method returns?.Can we get the entityId by the return of this method
    – vijay b
    Commented Mar 8, 2017 at 6:17
  • Do you know why $customer = $this->_objectManager->create('Magento\Customer\Model\Customer')->load($email,'email') not works? It returns null.
    – LucScu
    Commented May 23, 2017 at 6:34
  • 1
    Had to use \Magento\Customer\Model\CustomerFactory because when the email was not found instead of returning false or null it was breaking. error: "No such entity with email = xxx, websiteId = 1" . Any suggestions?
    – Mehdi
    Commented Dec 1, 2017 at 19:40
  • 1
    @Mehdi Surround it with a try-catch Block try { return $this->customerRepository->get($email, 1); } catch (NoSuchEntityException $e) { return null; } Commented Sep 13, 2018 at 15:52
  • 1
    @LucScu the Method you are searching for is called loadByEmail for ` Magento\Customer\Model\Customer` class Commented Sep 13, 2018 at 15:55
8

It is working fine, please use below code-

$CustomerModel = $objectManager->create('Magento\Customer\Model\Customer');
$CustomerModel->setWebsiteId(1); **//Here 1 means Store ID**
$CustomerModel->loadByEmail($customerEmail);
$userId = $CustomerModel->getId();
4
  • 4
    Welcome to Magento SE and thanks for your contribution. However, using the object manager is discouraged and even working directly with the models is considered deprecated by Magento. Best practise is using the service contracts (here: CustomerRepository::get()) and in this case they do what's needed, so there is no reason not to use them. Commented Jun 14, 2017 at 10:15
  • Its not working for me Commented Aug 29, 2018 at 8:08
  • setWebsiteId method is for set Store Id not Website ID, Really?
    – Greck
    Commented Sep 17, 2018 at 13:48
  • perfect answer!!! +1 made my day :) Commented Aug 18, 2021 at 9:38

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.