Get customer data by email id in magento 2
To get customer first name, last name, customer group and other data using Magento\Customer\Api\CustomerRepositoryInterface interface.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
<?php namespace CWM\Customer\Helper; class CustomerData extends \Magento\Framework\App\Helper\AbstractHelper { /* * \Magento\Customer\Api\CustomerRepositoryInterface */ protected $customerRepository; /** * @param \Magento\Framework\App\Helper\Context $context * @param \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository * @param $data */ public function __construct( \Magento\Framework\App\Helper\Context $context, \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository, array $data = [] ) { $this->customerRepository = $customerRepository; parent::__construct($context,$data); } /** * Retrieve Customer data from email by website level * * @return object * @throws \Magento\Framework\Exception\LocalizedException */ public function getCustomer($email,$websiteid = 1) { try { $customer = $this->customerRepository->get($email,$websiteid); } catch (Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__("The customer email isn't defined.")); } return $customer; } } |
Now from any file call this function and you can get customer data.
From template call helper function.
1 2 3 4 5 6 7 8 9 10 |
<?php $emailId = 'coffeewithmagento.in@gmail.com'; $customerHelper = $this->helper('CWM\Customer\Helper\CustomerData'); $customer = $customerHelper->getCustomer($emailId); if(!is_null($customer) && $customer->getId()){ echo $customer->getId(); echo '<pre>'; print_r($customer->getData()); echo '</pre>'; } |