Get Categories and Its Sub Categories in Magento

Get Categories and Its Sub Categories in Magento:

To retrieve categories and their subcategories in Magento, you can use Magento’s built-in repository classes and helper functions. Using the Magento\Catalog\Model\CategoryRepository and Magento\Catalog\Model\ResourceModel\Category\CollectionFactory, you can efficiently fetch category data, including subcategories, in a structured way. Here’s a basic approach:

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Framework\App\State;

class CategoryHelper
{
protected $categoryCollectionFactory;

public function __construct(
CollectionFactory $categoryCollectionFactory,
State $state
)
{
$this->categoryCollectionFactory = $categoryCollectionFactory;
$state->setAreaCode('frontend'); // Required if running in non-frontend context
}

public function getCategoriesWithSubcategories()
{
$categories = $this->categoryCollectionFactory->create()
->addAttributeToSelect(['name', 'is_active'])
->addAttributeToFilter('is_active', 1)
->setOrder('position', 'ASC');

$categoryData = [];
foreach ($categories as $category) {
if ($category->getParentId() == 2) { // Root category check
$subCategories = [];
foreach ($categories as $subCategory) {
if ($subCategory->getParentId() == $category->getId()) {
$subCategories[] = ['id' => $subCategory->getId(), 'name' => $subCategory->getName()];
}
}
$categoryData[] = [
'id' => $category->getId(),
'name' => $category->getName(),
'subcategories' => $subCategories
];
}
}
return $categoryData;
}
}

This method ensures that only active categories are retrieved, sorted in the desired order, and structured to include their subcategories efficiently. This approach is optimal for displaying category navigation menus, filters, or hierarchical category structures in Magento stores.