How to get a store in Magento 2 programmatically?

- Fire development, Magento 2

Magento 2 Development

In the article below we shed light on how to get a current store in Magento 2 programmatically. The following information is useful when you create a PHP script or Magento 2 module. Sometimes, it is necessary to check, which store is currently active or for which store you need to get or change values. The procedure is quite straightforward: you need only a few lines of code to do that. More tips from Magento 2 cookbook.


1) How to get a store in Magento 2 programmatically

In Magento 1, you can get a store and the current store programmatically quite simple:

As for Magento 2, the procedure looks as follows:


2) How to get a store in Magento 2 programmatically

Let’s explore how to get a current store in Magento 2 with every class that injects StoreManagerInterface. You can receive all the necessary store-related data from a current store manager. However, an object differs for each store frontend even if you call it from the backend. With the help of the following code, you can create a simple class that injects this store manager interface:

The getStoreId() method returns the ID from the current active Magento 2 store.

Different scope

Note that you can’t use isAdmin() to check if this code was called from the adminhtml context. While it was a common option in Magento 1, 2x has its algorithm. To check this information, use a method based on the \Magento\Framework\App\State class. First of all, you need to inject it. Next, call getAreaCode. You will get information on whether this class was called from the adminhtml of frontend or not. Below, you can see an example of a simple if statement for this case:

It checks if the area code equals adminhtml, which is defined as follows in \Magento\Backend\App\Area\FrontNameResolver:


As you can see, the procedure of getting a current store in Magento 2 differs from the one common to Magento 2. However, it is not difficult at all. For further information, follow these links:

Magento 2 get current store