Magento – Magento 2 : Change Store view programmatically at front end side

magento2magento2.3.1store-view

I want to change store view programmatically same as like when we switch store from store switcher at front end side.

I try this answer. But, it's not working. It's just change store view name from store switcher dropdown.

How to implement it?

Any help would be appriciated.

Best Answer

Try below solution to change store view programmatically

/**
 * @var \Magento\Store\Api\StoreCookieManagerInterface $_storeCookieManager
 */
protected $_storeCookieManager;

/**
 * @var \Magento\Store\Api\StoreRepositoryInterface $_storeRepository
 */
protected $_storeRepository;

public function __construct(
    \Magento\Store\Api\StoreCookieManagerInterface $storeCookieManager,
    \Magento\Store\Api\StoreRepositoryInterface $storeRepository
) {
    $this->_storeCookieManager = $storeCookieManager;
    $this->_storeRepository = $storeRepository;
}

public function execute(){
    $store = $this->_storeRepository->getActiveStoreByCode('store_view_code');
    $this->_storeCookieManager->setStoreCookie($store);
}
Related Topic