Magento – Get default store id from current website Magento 2

magento2multistorestore-view

I'm implementing module which will change the store id for current webiste but not the default store id like this:

$this->_storeManager->setCurrentStore($storeId);

In magento 2 backend i've configured default store view for my current website like this:

config store

the problem is i need to get this default store id from current website in my observer so i can do some function, roughly what i need like this:

$storeId = $this->getDefaultStoreId(); //this is what i need!!
$customStoreId = $this->getCustomStoreId(); //this is my function to get custom store id, nvm this
if($customStoreId){
  $this->_storeManager->setCurrentStore($customStoreId);
} else{
  $this->_storeManager->setCurrentStore($storeId);
} 

Best Answer

You can get current store id from below code:

$storeManager = $this->_objectManager->get('Magento\Store\Model\StoreManagerInterface');

$storeId = (int) $this->getRequest()->getParam('store', 0);

$store = $storeManager->getStore($storeId);

$storeManager->setCurrentStore($store->getCode());
Related Topic