How to Get Customer Groups in Magento 2

If you are finding a way to get all customer groups in Magento 2 then you are in a right place. This article is all about what you are looking for.

I assume that you already have module. So, first you need to create one class file, if you already have it then use that and add below code into your class.

Copy
/**
 *
 * @var \Magento\Customer\Model\ResourceModel\Group\Collection
 */
protected $customerGroups;
    
/**
 * ...
 * @param \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroups
 * ...
 */
public function __construct(
    ...
    \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroups,        
    ...
) {
    ...
    $this->customerGroups = $customerGroups;        
    ...
}
/**
 * 
 * @return array
 */ 
public function getCustomerGroups() {
    $customerGroups = $this->customerGroups->toOptionArray();
    return $customerGroups;
}

In above code getCustomerGroups will returns the array of all customer groups. So, you can use this function as per your need.

That’s it.

I hope this post helped you to find what you were looking for.

Bookmark it for your future reference. Do comment below if you have any other questions on that.

P.S. Do share this note with your team.

Review other articles maybe it'll help you too.