Magento 2How To GuideApril 28, 2024Simon Walker

How to Set, Retrieve & Unset Session Variable in Magento 2?

How to Set, Retrieve & Unset Session Variable in Magento 2?

If you wish to personalise the user experience and ensure your store remains ahead of the competition, you need to understand about session variables. A session is the time that a user spends on a website from logging in to logging out. It temporarily stores information related to the user’s activities while they browse the site.

When a user logs into a website, a session is created with unique session ID. Session variables are used to store temporary information, sometimes for retrieving and viewing data on multiple web pages. Knowing to how to retrieve this information is important if you are running an online store.

This article demonstrates the code to set and unset different types of sessions (Catalog, Customer, Checkout) in Magento 2 and how to retrieve information from them.

Why Are Sessions Important?

Why do you need to know about Magento 2 set session variable or the Magento 2 unset session variable? For this, you need to understand the importance of sessions.

1. User Differentiation

One of the top reasons you need to know about session variables is to identify the users. Whenever a session is started, the website assigns a unique ID to the user. As they interact with your website, you can easily map their journey with the session variable.

2. Personalisation

The next thing you would be wondering is why would anyone want to track a visitor’s journey. Well, personalisation is the key to success in eCommerce. A session variable helps the website store user-specific information. This could include their product preferences and other online shopping behaviour. With the help of this information, websites can target the user with relevant ads and product recommendations.

3. Authentication

Without session data storage, a user will need to provide authenticate at every step. It means they would need to keep adding their username and password. It can become extremely frustrating and undermine the user experience. Once the user authenticates their credentials at the start, a session helps ensure that there is no need to provide the same information repeatedly.

4. Shopping Cart Functionality

In eCommerce, sessions ensure seamless management of the shopping cart. A user will add, remove, or modify products in their cart as they browse your store. Without session variables, it is not possible. Given how important the shopping cart functionality is in eCommerce, we can safely conclude that knowing about sessions is mandatory.

Magento 2 Session Type

The following are the different types of session classes in Magento 2.


vendor/magento/module-catalog/Model/Session.php
 
vendor/magento/module-newsletter/Model/Session.php
 
vendor/magento/module-persistent/Model/Session.php
 
vendor/magento/framework/Message/Session.php
 
vendor/magento/module-customer/Model/Session.php
 
vendor/magento/module-backend/Model/Session.php
 
vendor/magento/module-checkout/Model/Session.php

Below is the code to deal with Catalog, Customer, and Checkout sessions using Dependency Injection (DI) and Object Manager methods.

Method 1: Dependency Injection

The following code will call Catalog, Customer, and Checkout sessions.

_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;
    }    
}
?>

Now, we set and get sessions from a template (.phtml) file.

$block->getCatalogSession()->setMyName('FME Extensions');
echo $block->getCatalogSession()->getMyName() . '
'; // output: FME Extensions $block->getCheckoutSession()->setTestData('Sample Data'); echo $block->getCheckoutSession()->getTestData() . '
'; // output: Sample Data $block->getCustomerSession()->setTestHello('Test Sample Data'); echo $block->getCustomerSession()->getTestHello() . '
'; // output: Test Sample Data

You can unset these sessions using the following code.

$block->getCatalogSession()->unsMyName();
$block->getCheckoutSession()->unsTestData();
$block->getCustomerSession()->unsTestHello();

From customer session, we can fetch customer information like customer name and email.

// get customer data
if ($block->getCustomerSession()->isLoggedIn()) {
    $customerId = $block->getCustomerSession()->getCustomerId();
    $customerData = $block->getCustomerSession()->getCustomer();
    echo $customerId . '
'; echo $customerData->getFirstname() . ' ' . $customerData->getLastname() . '
'; echo $customerData->getEmail() . '
'; print_r($block->getCustomerSession()->getCustomer()->getData()); }

From the checkout session, we can fetch quote information.

// get checkout session data
echo $block->getCheckoutSession()->getQuoteId();
print_r($block->getCheckoutSession()->getQuote()->getData());

Method 2: Using Object Manager

Use the following code to deal with session variables using Object manager.

$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();        
 
$catalogSession = $objectManager->get('\Magento\Catalog\Model\Session');
$customerSession = $objectManager->get('\Magento\Customer\Model\Session');
$checkoutSession = $objectManager->get('\Magento\Checkout\Model\Session');
 
// set session variables and their value
$catalogSession->setMyName('FME Extensions');
$checkoutSession->setTestData('Sample Data');
$customerSession->setTestHello('Test Sample Data');
 
// print session variables value
echo $catalogSession->getMyName() . '
'; // output: FME Extensions echo $checkoutSession->getTestData() . '
'; // output: Sample Data echo $customerSession->getTestHello() . '
'; // output: Test Sample Data // Unset session $catalogSession->unsMyName(); $checkoutSession->unsTestData(); $customerSession->unsTestHello();

Conclusion

These are easy and straightforward ways to set and unset sessions in Magento 2. If you have any questions, please don’t hesitate to contact us. Our Magento development experts will get back to you promptly.

Other Articles: