Magento 2: Get Customer Groups

This article shows how to get all customer groups name and id in Magento 2.

I will be showing an example in a Block class. You can write the code in other class (Helper/Model) as well.

Both ways (Dependency Injection & Object Manager way) are shown below.

Using Dependency Injection (DI)

Here is the code that you need to write in your Block class.


/**
 * 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();
	array_unshift($customerGroups, array('value'=>'', 'label'=>'Any'));
	return $customerGroups;
}

Using Object Manager


$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();		

$customerGroupsCollection = $objectManager->get('\Magento\Customer\Model\ResourceModel\Group\Collection');
$customerGroups = $customerGroupsCollection->toOptionArray();
//array_unshift($customerGroups, array('value'=>'', 'label'=>'Any'));
var_dump($customerGroups);

The output array while calling getCustomerGroups() method will be something like this:


Array
(
    [0] => Array
        (
            [value] => 
            [label] => Any
        )

    [1] => Array
        (
            [value] => 0
            [label] => NOT LOGGED IN
        )

    [2] => Array
        (
            [value] => 1
            [label] => General
        )

    [3] => Array
        (
            [value] => 2
            [label] => Wholesale
        )

    [4] => Array
        (
            [value] => 3
            [label] => Retailer
        )

)

Hope this helps. Thanks.