How do I get the category_id (or the Magento\Catalog\Model\Category itself) of the Root Category of a given Store in Magento 2 from a custom Model?
In Magento 1.x, I would have simply used
Mage::app()->getStore($storeId)->getRootCategoryId();
I have tried to get the Store object from the StoreManager, but I can't find any documentation for the Root Category
I found the answer myself. :-)
In \Magento\Store\Model\Store, there is a function getRootCategoryId()
namespace Vendor\Module\Helper;
public class Store
{
/**
* @var \Magento\Store\Model\StoreManagerInterface $storeManager
*/
protected $storeManager;
public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
$this->storeManager = $storeManager;
}//__construct
/**
* Get an associative array of [store_id => root_category_id] values for all stores
* @return array
*/
public function getAllStoreRootCategories()
{
$storeroots = [];
foreach ($this->storeManager->getStores() as $store) {
$storeroots[$store->getId()] = $store->getRootCategoryId();
}
return $storeroots;
}//getAllStoreRootCategories
/**
* Get the root category id of a store
* @param int|string|\Magento\Store\Model\Store $store The store to get category from, either by store_id, store_code or the \Magento\Store\Model\Store instance itself
* @return int root category of store
* @throws \Exception if no such store was found
*/
public function getStoreRootCategoryId($store)
{
# Get \Magento\Store\Model\Store instance by id
if (is_int($store)) {
$store = $this->storeManager->getStore($store);
}
# Get \Magento\Store\Model\Store instance by code
if (is_string($store)) {
foreach ($this->storeManager->getStores() as $storeModel) {
if ($storeModel->getCode() == $store) {
$store = $storeModel;
break;
}
}
}
# Get root category id from \Magento\Store\Model\Store instance
if ($store instanceof \Magento\Store\Model\Store) {
return $store->getRootCategoryId();
}
# If no \Magento\Store\Model\Store instance was supplied or found by id/code
throw new \Exception('No such store found: ' . var_export($store, true));
}//getStoreRootCategoryId
}//class Store
<?php
class your class_name
{
public function __construct(
\Magento\Store\Model\StoreManagerInterface $_storeManager
)
{
$this->_storeManager = $_storeManager;
}
public function getRootCategoryId()
{
$store = 1;
$rootCatId = $this->_storeManager->getStore($store)->getRootCategoryId();
//$rootCatId = $this->_storeManager->getStore()->getRootCategoryId();//without assign store id
}
}
Thanks Aron! so just to make it super easy to understand, if you are going to use this inside a module you should use direct injection as follows:
<?php
namespace ...
use ...
class Classname
{
/** @var \Magento\Store\Model\Store */
protected $_store;
public function __construct(
\Magento\Store\Model\Store $store
)
{
$this->_store = $store;
}
public function getRootCategoryId()
{
return $this->_store->getStoreRootCategoryId();
}
}