Magento 2 How to Get All The Customer Groups

In Magento 2, if you want to get all the customer groups, you need to use the following code snippet:
You need to create a Block class where you can call getCustomerGroups() method to get all the customer groups in Magento.

/**
 * Customer Group
 *
 * @var \Magento\Customer\Model\ResourceModel\Group\Collection
 */
protected $customerGroup;
    
/**
 * @param \Magento\Backend\Block\Template\Context $context
 * @param \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroup
 * @param array $data
 */
public function __construct(
    \Magento\Backend\Block\Template\Context $context,
    \Magento\Customer\Model\ResourceModel\Group\Collection $customerGroup,        
    array $data = []
) {
    $this->customerGroup = $customerGroup;        
    parent::__construct($context, $data);
}
/**
 * Get customer groups
 * 
 * @return array
 */ 
public function getCustomerGroups() {
    $customerGroups = $this->customerGroup->toOptionArray();
    return $customerGroups;
}

If you want to create a customer programmatically, you can follow this link.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s