Get Category Collection in Magento 2

Posted on

Use the ResourceModel\Category\CollectionFactory if you need a collection by category. Example:

<?php
declare(strict_types=1);
namespace Vendor\Module\Model;

use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as CategoryCollectionFactory;

class YourClass
{
    protected $categoryCollection;

    public function __construct(
        CategoryCollectionFactory $categoryCollection
    ) {
        $this->categoryCollection = $categoryCollection;
    }

    protected function getCategoryCollection()
    {
        $collection = $this->categoryCollection->create();
        $collection->addAttributeToSelect(['name', 'is_active']);

        foreach ($collection as $item) {
            // echo $item->getName();
        }

        return $collection;
    }
}

Tested in Magento 2.4.3