How to Get Category Tree Collection in Magento 2?

Get Category tree collection by the specific root category id Magento 2.

Magento has the interface to get the category tree by the Magento\Catalog\Api\CategoryManagementInterface with getTree() method.

Check the definition of the method from the interface,

If you have passed $rootCategoryId value, the result will be a tree for that category id otherwise it will return all the category tree for the store.

$depth indicates how many depths for the result.

You can explore the category tree by passing Category id you want to show as tree format,

Category with the child category will be display as children_data in the output.

Output:
Magento\Catalog\Api\Data\CategoryTreeInterface

Leave a Reply