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.

How to reindex indexer programmatically in magento 2?

Just create PHP file under your module’s Cron folder,
A created module like Rbj_Indexing for reference, Create Indexer.php file and call execute() function,

<?php
namespace Rbj\Indexing\Cron;

class Indexer
{
    public function __construct(
        \Magento\Indexer\Model\Processor $processor
    ) {
        $this->processor = $processor;
    }

    public function execute()
    {
        /* Regenerate indexes for all indexers */
        $this->processor->reindexAll();

        /* Regenerate indexes for all invalid indexers */
        $this->processor->reindexAllInvalid()
    }
}

There are two types of method for indexing.

1. Regenerate indexes for all indexers
$this->processor->reindexAll();

2. Regenerate indexes for all invalid indexers. This will only regenerate for invalid indexer.
$this->processor->reindexAllInvalid()