Magento 2 current customer group

Today we talk about how in Magento 2 current customer group. This tutorial includes example of get current customer group id, get current customer group name and other group information. Magento 2 use the model session for storing the current session data. You have to inject \Magento\Customer\Model\Session to get current customer session data and inject \Magento\Customer\Model\Group to get customer group data. So let start with our example.

Dependency Injection

protected $_customerSession;
protected $_customerGroupCollection;

public function __construct(
           
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Customer\Model\Group $customerGroupCollection,

    ) {


        $this->_customerSession = $customerSession;
        $this->_customerGroupCollection = $customerGroupCollection;

    }

public function getGroupId(){
 if($this->_customerSession->isLoggedIn()):
   //Get current group
        echo $customerGroupId = $this->_customerSession->getCustomer()->getGroupId();
                $groupCollection = $this->_customerGroupCollection->load($customerGroupId);
        echo $groupCollection>getCustomerGroupCode();//Get current customer group name
    endif;

}

Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

if ($customerSession->isLoggedIn()) {

//Get current group
        echo $customerGroupId = $customerSession->getCustomer()->getGroupId();
                $groupCollection = $objectManager->create('\Magento\Customer\Model\Group')->load($customerGroupId);
        echo $groupCollection->getCustomerGroupCode();//Get current customer group name
   }

Qaisar Satti

Hi, I'm Qaisar Satti! I've been a developer for over 20 years, and now I love sharing what I've learned through tutorials and guides. Whether you're working with Magento, PrestaShop, or WooCommerce, my goal is to make your development journey a bit easier and more fun. When I'm not coding or writing, you can find me exploring new tech trends and hanging out with the amazing developer community. Thanks for stopping by, and happy coding!

Leave a Reply