3

I got customer collection with help of objectManager but I don't know how to get customer collection via injecting a class in constructor(Dependency Injection).

So how we get customer collection using DI or factory method in Magento 2?

11

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);
}
  • 4
    That works but loading the customer model is not necessary. Inject the autogenerated factory instead: \Magento\Customer\Model\ResourceModel\Customer\CollectionFactory and use $this->customerCollectionFactory->create() to get a new collection. – Fabian Schmengler Jul 6 '17 at 6:12
  • could u please elaborate with a code Fabian... It will be helpful – Varun S Jul 6 '17 at 6:21
  • This works but it don't brings the custom customer attributes into the array. Neither loading the customer model with id is unable to fetch custom customer attributes into the array. – Kumar A. May 21 '18 at 15:17
  • getCustomer function is not working – jafar pinjar Aug 3 '18 at 9:33

Not the answer you're looking for? Browse other questions tagged or ask your own question.