You can get the current store code from the browser cookie using Magento.
Sometimes you required to detect store code before any request generated in a store and that time you will help this article. You can check the current store code in beforeDispatch() method of the request and verify for the current store code.
Interface Provides the functionality:
Magento\Store\Api\StoreCookieManagerInterface
<?php namespace Jesadiya\StoreCodeFromCookie\Model; use Magento\Store\Api\StoreCookieManagerInterface; use Magento\Framework\Exception\LocalizedException; class StoreCode { /** * @var StoreCookieManagerInterface */ private $storeCookieManager; public function __construct( StoreCookieManagerInterface $storeCookieManager ) { $this->storeCookieManager = $storeCookieManager; } /** * Get Store code by cookie * * @return String|null */ public function getStoreCodeByCookie(): ?string { $storeCode = $this->storeCookieManager->getStoreCodeFromCookie(); if ($storeCode) { // fetch store info by store repository interface } return $storeCode; } }
Magento Fetch the store code by cookie using cookie value “store”
When you check the class, Magento\Store\Model\StoreCookieManager, one constant is defined as
const COOKIE_NAME = ‘store’;
StoreCookieManagerInterface mapped to StoreCookieManager Class and the function code is,
public function getStoreCodeFromCookie() { return $this->cookieManager->getCookie(self::COOKIE_NAME); }
Output:
If Browser contains the cookie value equals to “store” it will store your current store code value.