In magento 2 How to get all customer data without using object manager? [closed]
-
23-01-2021 - |
Question
In customer module need to show all customer data whatever I want?
Solution
1) Use \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory class to get customer collection
<?php
protected $_customerFactory;
public function __construct(
...
\Magento\Customer\Model\ResourceModel\Customer\CollectionFactory $customerFactory
...
) {
...
$this->_customerFactory = $customerFactory;
...
}
/**
* Get customer collection
*/
public function getCustomerCollection()
{
return $this->_customerFactory->create();
}
Then you can call:
<?php
$customerCollection = $this->getCustomerCollection();
foreach ($customerCollection as $customer) {
echo $customer->getEmail();
}
2) Use \Magento\Customer\Api\CustomerRepositoryInterface class to get customer by customerId or customer email
protected $_customerRepositoryInterface;
public function __construct(
....
\Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
....
) {
....
$this->_customerRepositoryInterface = $customerRepositoryInterface;
}
/**
* Get Customer by id
*/
public function getCustomer($customerId)
{
return $this->_customerRepositoryInterface->getById($customerId);
}
/**
* Get Customer by email
*/
public function getCustomerByEmail($customerEmail)
{
return $this->_customerRepositoryInterface->get($customerEmail);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange