Hello Devs,
In today’s Quick tutorial, we will see how to get all stores lists programmatically in Magento 2.
Default Magento provides one Magento website, store, and store views.
This information is usually stored in the “store” table of your Magento 2 database.
Magento provides StoreRepositoryInterface to fetch all store lists and store-related information :
Magento\Store\Api\StoreRepositoryInterface
Using this repository we can fetch store-related information like store_id, code, website_id, group_id, name, sort_order, and is_active.
See example below :
<?php
namespace Jigar\Tutorials\Block;
use \Magento\Store\Api\StoreRepositoryInterface;
class Example
{
/**
* @var \Magento\Store\Api\StoreRepositoryInterface
*/
protected $storeRepository;
/**
* @param \Magento\Store\Api\StoreRepositoryInterface $storeRepository
*/
public function __construct(
\Magento\Store\Api\StoreRepositoryInterface $storeRepository
) {
$this->storeRepository = $storeRepository;
}
/**
* {@inheritdoc}
*/
public function getAllStoresList()
{
$stores = [];
foreach ($this->storeRepository->getList() as $store) {
$stores[] = $store->getData();
}
return $stores;
}
/**
* {@inheritdoc}
*/
public function getAllActiveStoresList()
{
$stores = [];
foreach ($this->storeRepository->getList() as $store) {
if ($store->isActive()) {
$stores[] = $store->getData();
}
}
return $stores;
}
}
In the above example, We can see we have created 2 functions,
- getAllStoresList() – Will return all stores lists – with store-related information
- getAllActiveStoresList() – will return all active store list
Sample Output :
[
[
"store_id" => "0",
"code" => "admin",
"website_id" => "0",
"group_id" => "0",
"name" => "Admin",
"sort_order" => "0",
"is_active" => "1",
],
[
"store_id" => "1",
"code" => "default",
"website_id" => "1",
"group_id" => "1",
"name" => "Default Store View",
"sort_order" => "0",
"is_active" => "1",
],
]
You can change the function logic as per your requirement.
That’s it for this tutorial, Do not missout to check below useful tutorials.
How to clear previous messages in MessageManager programmatically?
Add Yes/No Attribute in Magento 2 programmatically
Securely render Javascript inside Magento 2 template files using PHP
Thank You!!
Leave a Comment