Magento 2 – get customer collection
In this tutorial I show you how to get customer collection. If you want to programmatically change or get customers, this will be the obvious way to get customer objects. With a collection you can filter all shop customers by attributes.
Magento 2 – get customer collection
In Magento you can get a collection of objects by simply call object->getCollection(). If you want a customer collection you may do the following code:
1 | $customerCollection = $customer->getCollection(); |
But how do you get a customer object?
Get customer object
Magento 2 offers you multiple methods on how to get an object. You get it from a factory, repository, by object manager or by direct inject it. My preferred method is factory, but you can do it any way you like. Remember: the object manager is simple, but not the best way – try to avoid this method. In the following lines of code I show you how to inject customer factory and customer object.
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 | class MyClass { 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" => "Max")) -load(); } } |
Please note, that it is nonsense to inject both Customer and CustomerFactory, but I only want to demonstrate that you can do exactly the same with each of these objects. The first method getCustomerCollection() simply returns a loaded collection of all customers with all attributes. Please note, that may not be a good idea if you have a lot of them (memory limit!). The second method getFilteredCustomerCollection() shows how do this from a given customer factory. You just need to add create(). I also add a filter to demonstrate how to filter your collection. This time we get a collection of all customers with a firstname like Max.
Conclusion
As you can see, it is quite easy to get a customer collection in Magento 2. You can inject needed classes in every construct method of your own class. You can do it in controller, block, helper or models… everywhere! Don’t forget to setup:di:compile if you change dependency injection. Otherwise you may get a “PHP Fatal error: Uncaught TypeError: Argument 1 passed to” exception.
Hi there,
Are you sure about using load() in the functions getFilteredCustomerCollection() and getCustomerCollection(). I think it should be getData();