Magento 2 – How to Get Category Name and Category Tree

categorycategory-productscategory-treemagento2

Magento 2.2.7

I have to output category name and "tree" or path for product.
For instance if my product is in category Lg775 my output should be:
Hardware/Motherboards/Intel/Lg775

so far I have this code that gives me category ID:

 //Load the product categories
 $categories = $product_data->getCategoryIds();
 //Select the last category in the list
 $categoryId = end($categories); 

Thank you all Magento experts for all the help so far! I really appreciate it 🙂


UPDATE – Solved

So I used the answer I checked however I had to modify the code so here is my code how to get full category path for "categoryID"

<?php

namespace Vendor\Module\Helper;


class CategoryTree {

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    private $categoryRepository;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\Tree
     */
    private $tree;

    public function __construct(
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        \Magento\Catalog\Model\ResourceModel\Category\Tree $tree,
        \Magento\Store\Model\StoreManagerInterface $storeManager) {
       $this->tree = $tree;
       $this->categoryRepository = $categoryRepository;
       $this->storeManager = $storeManager;
    } // end of function __construct


    public function getTreeByCategoryId($categoryId)
    {
        $storeId = $this->storeManager->getStore()->getId();
        $category = $this->categoryRepository->get($categoryId, $storeId);
        $categoryTree = $this->tree->setStoreId($storeId)->loadBreadcrumbsArray($category->getPath());

        $categoryTreepath = array();
        foreach($categoryTree as $eachCategory){
            echo $eachCategory['name'];
            $categoryTreepath[] = $eachCategory['name'];
        }
      $categoryTree = implode(" &gt; ",$categoryTreepath);
      return $categoryTree;
    } // end of function getTreeByCategoryId

} // end of class

later I called that class like this:

      $categoryObject=\Magento\Framework\App\ObjectManager::getInstance();
      $category=$categoryObject->create('Vendor\Module\Helper\CategoryTree');
      $categoryTreepath=$category->getTreeByCategoryId($categoryId);
      var_dump($categoryTreepath);

The result was just what I needed 🙂 Thank you all!

Best Answer

If you want to get a particular category tree you have to use below method

Magento\Catalog\Model\ResourceModel\Category\Tree::loadBreadcrumbsArray($path, $addCollectionData = true, $withRootNode = false);

As per this method definition, you have to provide category path $path, of your category instead category ID.

So, first, you have to get category path by category id then load and after that get category tree by tree.

Code:

<?php

namespace StackExchange\Magento\Model;


class CategoryTree {

    /**
     * @var \Magento\Store\Model\StoreManagerInterface
     */
    private $storeManager;

    /**
     * @var \Magento\Catalog\Api\CategoryRepositoryInterface
     */
    private $categoryRepository;

    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\Tree
     */
    private $tree;

    public function __construct(
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        \Magento\Catalog\Model\ResourceModel\Category\Tree   $tree ,
        \Magento\Store\Model\StoreManagerInterface $storeManager    
   ) {

       $this->tree = $tree;
       $this->categoryRepository = $categoryRepository;
       $this->storeManager = $storeManager;
    }
    public function getTreeByCategoryId()
    {
        $storeId = $this->storeManager->getStore()->getId();
        $categoryId = 45;
        $category = $this->categoryRepository->get($categoryId, $storeId);
        $categoryTree = $this->tree->setStoreId($storeId)->loadBreadcrumbsArray($category->getPath());

        $categoryTreepath = '';
        foreach($categoryTree as $eachCategory){
             echo $category['name'];
            echo '<pre>';
            print_r($eachCategory);
           $categoryTreepath = $categoryTreepath. '/'.$category['name'];
        }
    }
}