How to get Customer Collection in Magento 2

Steps to get Customer Collection in Magento 2

Get customer object

Below is the code which you can use to inject customer factory and customer object.

class NewClass 
{
    protected $_customer;
    protected $_customerFactory;

    public function __construct(...
                                \Magento\Customer\Model\CustomerFactory $customerFactory,
                                \Magento\Customer\Model\Customer $customers
    )
    {
        ...
        $this->_customerFactory = $customerFactory;
        $this->_customer = $customers;
    }

    public function getCustomerCollection() {
        return $this->_customer->getCollection()
               ->addAttributeToSelect("*")
               ->load();
    }

    public function getFilteredCustomerCollection() {
        return $this->_customerFactory->create()->getCollection()
                ->addAttributeToSelect("*")
                ->addAttributeToFilter("firstname", array("eq" => "John"))
                -load();
    }
}

Get customer detail

To get the detail of the customer, you will require their ID as the customer collection require to be loaded by customer ID.

$customerID = 10;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerObj = $objectManager->create('Magento\Customer\Model\Customer')
->load($customerID);
$customerEmail = $customerObj->getEmail();

 

 

If you are looking for Magento Developers, Visit Magento Development Agency.