How to Get, Set and Unset Custom Session Variable in Magento 2

How to Get, Set and Unset Custom Session Variable in Magento 2

A session is a way of storing variables and making them available on multiple pages on a website. In other words, a session is a temporary object that is created on the server for each Magento 2 store users to store some values, i.e., items in a cart.

The session enables you to build more customized applications and increase the appeal of your website visually, and it is a way to preserve certain data across subsequent accesses. 

Sometimes while Magento 2 module customization or Magento 2 module development, you may need to get set and unset custom session variable in Magento 2.

For instance, once the user registers in our store, it stores the customer’s first name, last name, id using session. Still, if you want to store additional information of the customer, i.e., age, then you have to use the method to get and set a custom session variable in Magento 2.

Suppose an owner wants a functionality where the popup should be displayed until the customer is logged in to the Magento 2 store. In that case, you have to unset the session variable when the customer logs out.

Check out the below method for the same:

Method to Get Set and Unset Custom Session Variable in Magento 2

  1. Use the below code in your block file.
  2. Now, we set and get session from template file.
  3. To Unset session variable

You can also find all details from customer session, checkout session, quote related details and sessions of catalog , backend, newsletter.

That’s it.

Any doubts? Do mention them in the Comments section below.

I would be glad to help you out.

Also, please share the solution with Magento Community via social media.

Thank you.

Get Weekly Updates

Never miss Magento tips, tricks, tutorials, and news.

Thank you for subscribing.

Something went wrong.

5
(based on 11 Reviews)

Krishna is a Magento developer at Meetanshi. She is always ready to learn new things. Apart from work, she likes to read books and spend time with family.

Leave a reply:

Your email address will not be published.