Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top