Tutorialsplane

Magento 2 Get Set Session Variable


Magento 2 Get Set Session Variable– We can use object manager to create sessions in magento2. Here in this tutorial, we are going to explain how you can set, Unset session variable on phtml, controller block or model.


Magento 2 Get Set Session Variable | Unset Example

We can manage session variables in Magento using object manager simply as below-

Set Session Variable – Set Catalog | Customer | Checkout Session

You can set Catalog,Customer and Checkout session simply as below-

Magento 2 Get Set Session Variable Example:

$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 variable
$catalogSession->setMyTestVariable1('ABC');
$checkoutSession->setMyTestVariable2('DEF');
$customerSession->setMyTestVariable3('GHI');

Get Session Variable – Get Catalog | Customer | Checkout Session

You can get Catalog,Customer and Checkout session simply as below-

Magento 2 Get Set Session Variable Example:

$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');

// sget session variable
$catalogSession->getMyTestVariable1();
$checkoutSession->setMyTestVariable2();
$customerSession->setMyTestVariable3();

Unset Session Variable

You can destroy session variable in magento2 simply as below-

Destroy Session Variable Example:

$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');

// sget session variable
$catalogSession->unsMyTestVariable1();
$checkoutSession->unsMyTestVariable2();
$customerSession->unsMyTestVariable3();