5

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 ?

15

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);
  • What is this get method returns?.Can we get the entityId by the return of this method – vijay b Mar 8 '17 at 6:17
  • Do you know why $customer = $this->_objectManager->create('Magento\Customer\Model\Customer')->load($email,'email') not works? It returns null. – LucScu May 23 '17 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 Dec 1 '17 at 19:40
  • 1
    @Mehdi Surround it with a try-catch Block try { return $this->customerRepository->get($email, 1); } catch (NoSuchEntityException $e) { return null; } – Lukas Komarek Sep 13 '18 at 15:52
  • 1
    @LucScu the Method you are searching for is called loadByEmail for ` Magento\Customer\Model\Customer` class – Lukas Komarek Sep 13 '18 at 15:55
3

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();
  • 2
    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. – Fabian Schmengler Jun 14 '17 at 10:15
  • Its not working for me – jafar pinjar Aug 29 '18 at 8:08
  • setWebsiteId method is for set Store Id not Website ID, Really? – Greck Sep 17 '18 at 13:48

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.