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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | /** * 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
1 2 3 4 5 6 | $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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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.





Mukesh Chapagain is a graduate of Kathmandu University (Dhulikhel, Nepal) from where he holds a Masters degree in Computer Engineering. Mukesh is a passionate web developer who has keen interest in open source technologies, programming & blogging.