Monday, July 4, 2022
HomeMagentoMagento 2 Get Category Collection by Id

Magento 2 Get Category Collection by Id

In this article, you going to see discussion regarding Magento 2 Get Category Collection by Id in detail and step by step.

If you are looking for this topic then you are at right place.

Let’s start with topic of Magento 2 Get Category Collection by Id

You can get category collection using new module or by using existing module.

Create the template file in module.

In the template file call the block.

Using this block file you can get category collection by Id.

Below is the code snippet.

$categoryId = 10; // category id
$getCategory = $block->getCategoryById($categoryId);
echo $getCategory->getName();echo "<br>";
echo $getCategory->getUrlKey();echo "<br>";
echo $getCategory->getIsActive();echo "<br>";
echo "<pre>";print_r($getCategory->getData());

Below is the code snippet for block file.

Using the class file called CategoryRepository file get the category collection.

In that block file create method in which pass the id of category.

Path for class file called CategoryRepository file get the category collection is given below.

<?php
namespace Techone\Category\Block;

class Category extends \Magento\Framework\View\Element\Template
{
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\CategoryRepositoryInterface $categoryRepository,
        array $data = []
    ) {
        $this->categoryRepository = $categoryRepository;
        parent::__construct($context, $data);
    }

    /* $categoryId as category id */
    public function getCategoryById($categoryId){
        try {
            return $category = $this->categoryRepository->get($categoryId);
        } catch (\Magento\Framework\Exception\NoSuchEntityException $e) {
            return ['response' => 'Category Not Found'];
        }
    }
}

In above above code snippet you see that how category Repository is used for getting category collection.

Pass the category id to created public method for getting category collection.

Call this method in template file for getting category collection.

Magento 2 get product collection by product SKU

Conclusion:

Using above code snippet you can get Category Collection by Id.

I hope you like this article and if you have any query, please comment below.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular