Site icon Qaisar Satti's Blogs

Magento 2 current customer group

Magento 2 current customer group

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
   }
Exit mobile version