How to Create, Read, Update and Delete Custom Cookie in Magento 2

custom_cookie_magento_2

Do you want to know how to create, read, update and delete the custom cookie in Magento 2? A cookie is very important for a PHP application. As such, Magento developer often needs a cookie to be store in the client browser to track and read particular behaviour of the visitor.

Today we will see how to create, read, update and delete the cookie in Magento 2 using PHP code and using JS code.

Create, Read, Update and Delete Cookie using PHP

In this example, I’m showing how to manage cookie in observer class. You can use this code snippet in any of your custom module class.

<?php
namespace Codextblog\Customcookie\Observer\Frontend\Customer;

use Magento\Framework\Stdlib\Cookie\CookieMetadataFactory;
use Magento\Framework\Stdlib\CookieManagerInterface;
use Magento\Store\Api\Data\StoreInterface;

class Makemycookie implements \Magento\Framework\Event\ObserverInterface
{
const COOKIE_NAME = 'CUSTOMER_GROUP_ID';

public function __construct(
        CookieMetadataFactory $cookieMetadataFactory,
        CookieManagerInterface $cookieManager,
        StoreInterface $store
    ) {
        $this->cookieMetadataFactory = $cookieMetadataFactory;
        $this->cookieManager = $cookieManager;
        $this->store = $store;
    }

public function execute(
        Observer $observer
    ) {
        $store = $this->store;
        $customer = $observer->getEvent()->getCustomer();
        /*CREATE OR UPDATE COOKIE*/
        $this->setStoreCookie($store, $customer);
        /*READ COOKIE*/
        $this->getStoreCookie();
        /*DELETE COOKIE*/
        $this->deleteStoreCookie($store);
      }
public function setStoreCookie($store, $customer)
    {
        $cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata()
            ->setHttpOnly(true)
            ->setDurationOneYear()
            ->setPath('/');

        $this->cookieManager->setPublicCookie(self::COOKIE_NAME, $customer->getGroupId(), $cookieMetadata);
    }

public function getStoreCookie()
    {
        return $this->cookieManager->getCookie(self::COOKIE_NAME);
    }

public function deleteStoreCookie($store)
    {
        $cookieMetadata = $this->cookieMetadataFactory->createPublicCookieMetadata()
            ->setPath($store->getStorePath());

        $this->cookieManager->deleteCookie(self::COOKIE_NAME, $cookieMetadata);
    }
}

Create, Read, Update and Delete Cookie using JS

Create one custom js file and call that file in your phtml template. In one of the article we have already seen how to call custom js file in Magento 2.


define([
    'jquery',
    'mage/cookies'
], function ($) {
/** create cookie */

    $.cookie('CUSTOMER_GROUP_ID', "1", { expires: 7, path: '/' });

/** update cookie */

    $.cookie("CUSTOMER_GROUP_ID", "2");

/** read cookie */

    $.cookie('CUSTOMER_GROUP_ID');

/** delete cookie */

    $.cookie("CUSTOMER_GROUP_ID", null);

});

Leave a Comment

(0 Comments)

All the comments are goes into moderation before approval. Please do not spam. Your email address will not be published. Required fields are marked *

Enjoy this post? Please support Us!

Follow us on twitter for daily new updates..

 

Want to become
a Magento 2 Expert?

If Yes! Then Subscribe to our newsletter and get weekly article to you email id.
Subscribe Here
SUBSCRIBE NOW
close-link

To Avoid Spam Downloads, We Want Your Email

We will send you download link right
away. Please submit form below.
SEND ME DOWNLOAD LINK
Close