8

I have tried to get all the stores in Magento 2.

$stores = $this->storeManager->getStores();
$ids= array();
foreach ($stores as $storeId => $storeData) {
    $ids[] = $storeId;
}

print_r($ids);

output returns 1.

But in DB it has two store codes "admin" and "default":

stores in DB

How do I get both stores ids?

2 Answers 2

4

Try this:

$ids = array_keys($this->storeManager->getStores(true));

The first (optional) parameter makes the StoreManager include the default store (which has ID 0). Furthermore, the keys of the returned array will be the store IDs so you may get them quickly by using array_keys().

12

You can use a default Magento store repository \Magento\Store\Api\StoreRepositoryInterface. Add it as dependency and call the getList method.

/** @var \Magento\Store\Api\StoreRepositoryInterface $repository */
$stores = $repository->getList();
foreach ($stores as $store) {
    echo 'Store: ' . $store->getId();
    echo ' --- ';
}

will output all ids:

output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.