How to Get Customer Collection in Magento 2
If you are a Magento 2 developer and ever need a list of customers, here’s the solution for you.
The below solution can be used to get customer collection in Magento 2. You can use this code when you need to implement features based on customers or their attributes.
For example, you would want to offer a special discount code based on customer groups or offer a first-time coupon code for customers who have not placed an order on your site yet.
Or you want to implement a condition based on the first name, last name, DOB, gender, etc. every time you want to do such customization, you will have to get customer collection in Magento 2 first.
Check the solution for the same.
Method to Get Customer Collection in Magento 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
use Magento\Customer\Model\Customer class ClassName { protected $customerCollection; public function __construct(Customer $customerCollection) { $this->customerCollection = $customerCollection; } public function getCustomerCollection() { return $this->customerCollection->getCollection() ->addAttributeToSelect("*") ->load(); } } |
Method to Get Customer Collection with Filter Based on Attributes:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
use Magento\Customer\Model\CustomerFactory class ClassName { protected $customerFactory; public function __construct(CustomerFactory $customerFactory) { $this->customerFactory = $customerFactory; } public function getCustomerCollection() { $firstname = 'xyz'; return $this->customerFactory->getCollection() ->addAttributeToFilter("firstname", $firstname)) -load(); } } |
Any doubts about the solution can be mentioned in the Comments section below. I’d be happy to help.
Also, please share the post with the Magento Community via social media.
Thank you.
Sanjay Jethva
Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe.
His passion for Magento 2 and Shopify solutions has made him a trusted source for businesses seeking to optimize their online stores. He loves sharing technical solutions related to Magento 2 & Shopify.
Prev
How to Set and Get Admin Session Quote in Magento 2
How to Add Image Field and Preview Image in Magento 2 Admin UI Component Form
Next