How to Set, Unset and Retrieve custom session variable value in magento 2

A session is storing variables and retrieving the variables on multiple pages on a website according to the different type of session. In other words, session is temporary storing space where user can store their custom additional information ex items data in shopping cart, personal information like age, sex, company name etc.

Following is the code which need to add in your custom module block file in magento 2.

namespace Vendor\Module\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{    
    protected $_catalogSession;
    protected $_customerSession;
    protected $_checkoutSession;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\Session $catalogSession,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Checkout\Model\Session $checkoutSession,
        array $data = []
    )
    {        
        $this->_catalogSession = $catalogSession;
        $this->_checkoutSession = $checkoutSession;
        $this->_customerSession = $customerSession;
        parent::__construct($context, $data);
    }
    
    public function _prepareLayout()
    {
        return parent::_prepareLayout();
    }
        
    public function getCatalogSession() 
    {
        return $this->_catalogSession;
    }
    
    public function getCustomerSession() 
    {
        return $this->_customerSession;
    }
    
    public function getCheckoutSession() 
    {
        return $this->_checkoutSession;
    }    
}

Use following code to set the custom session variable in your phtml template file in magento 2.

$block->getCatalogSession()->setYourName('Magespider Solutions');
$block->getCheckoutSession()->setTestCheckoutData('Hello World!');

Use Following code to get the custom session variable value in your phtml template file in magento 2.

echo $block->getCatalogSession()->getYourName();
echo $block->getCheckoutSession()->getTestCheckoutData();

Use Following code to unset custom session variable.

$block->getCatalogSession()->unsYourName();
$block->getCheckoutSession()->unsTestCheckoutData();

That’s it.

If you have any question then please share your doubts by following below form.

Thank you.

Leave a Reply

Your email address will not be published. Required fields are marked *