How to get Category collection by Category id in magento 2?

You can get category collection by category id by below code snippet,

<?php
namespace Rbj\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'];
        }
    }
}

Call From template file, Pass argument as Category id,

$categoryId = 5; // 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());

 

 

How to get Category Collection per Storewise in Magento 2?

When we have multi-store setup and store have different category assigned at that time we need to get store wise category collection.
We can get store wise category collection by below code snippet.

1. Use directly Objectmanager is not best/Recommended way to do in Magento, use Block with the construct() and fetch method in your phtml file.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$categoryFactory = $objectManager->create('Magento\Catalog\Helper\Category');
$categoryFactory->getStoreCategories(false,false,true);

2. Recommended Way Using Create Block file and call from the template,

Create Block PHP file,

<?php
namespace Rbj\Training\Block\Index;

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

     /**
     * Retrieve current store level 2 category
     *
     * $sorted (if true display collection sorted as name otherwise sorted as based on id asc)
     * $asCollection (if true display all category otherwise display second level category menu visible category for current store)
     * $toLoad
     */
    public function getMainStoreCategories($sorted = false, $asCollection = false, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }

    /* Here we have passed sorted as true so category display as Name ASC order */
    public function getAllCurrentStoreCategories($sorted = true, $asCollection = true, $toLoad = true)
    {
        return $this->_categoryHelper->getStoreCategories($sorted , $asCollection, $toLoad);
    }
}

Display second level category, all those categories which have Level equals 2. call below function from a template file,

$getLevel2Category = $block->getMainStoreCategories();
foreach($getLevel2Category as $category) {
    echo $category->getName();echo "<br>";
}

For getting all categories of current store call below function in template file,

$getCategory = $block->getAllCurrentStoreCategories();
foreach($getCategory as $category) {
    echo $category->getName();echo "<br>";
}

You can change the custom argument by passing argument on above function from template file.

Error during compilation, Incompatible argument type: Required type: \Magento\Framework\DB\Adapter\AdapterInterface.

We can be resolved Compile time error by below way, The error looks like when running compilation command,

Incompatible argument type: Required type: \Magento\Framework\DB\Adapter\AdapterInterface. Actual type: string; File:
app/code/Rbj/CustomForm/Model/ResourceModel/Customform/Grid/Collection.php
[Magento\Framework\Validator\Exception]
Error during compilation

Solutions:

From Magento 2.2.* version we need to pass full class name in__construct()  instead of $connection = null as di argument in Collection.php file.

Replace, $connection = null argument with \Magento\Framework\DB\Adapter\AdapterInterface $connection = null  in __construct() parameter.

Run again command,
php bin/magento setup:di:compile
an error will be gone.