Magento 2 Category Collection – How to Get Category Collection per Store

categorymagento2model

I want to get all categories names from a specific store. I'm trying:

$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()                              
    ->addAttributeToSelect('*')
    ->setProductStoreId($store->getId());

    foreach ($categories as $category){
        $category->getName();
    }

But it shows all the categories in the same language (same-store view).

So ->setProductStoreId($store->getId()) doesn't work.

I'm also tried $category->setStoreId($store->getId())->getName().

How can I get all the categories names for specific store view?

Best Answer

Try this :

protected $_storeManager;

public function __construct(
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    $data = []
) {
    $this->_storeManager = $storeManager;
    parent::__construct($data);
}

$objectManager = $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Model\ResourceModel\Category\CollectionFactory');
$categories = $categoryFactory->create()                              
    ->addAttributeToSelect('*')
    ->setStore($this->_storeManager->getStore()); //categories from current store will be fetched

foreach ($categories as $category){
    $category->getName();
}