🔥 Just Launched! Werra Premium Template for HyväSee it in Action

How to Get Customer Collection in Magento 2

By Sanjay JethvaUpdated on Jul 16, 2025 2 min read

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:

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();
    }
}

One step ahead, if you want to get customer collection filtered by attribute, for example, only get customer collection whose gender is female, or whose customer account was created on a specific date, you can do so using the below solution:

Method to Get Customer Collection with Filter Based on Attributes:

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();
    }
}

That’s it.

Also, please share the post with the Magento Community via social media.

Thank you.

Sanjay Jethva Full Image
Article bySanjay 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.