In this tutorial, Today I will explain to how to reindexing programmatically in Magento 2. Sometimes, We’re performing some customization programatically like product price update, change product category etc. & then you need to reindexing product at that time, you can add reindexing programmatically. This below command will helpful to indexing reindex. After that, you don’t need to execute command.
You may also like this :
You can follow this below way to do all indexer reindex in Magento 2 :
First of all, Let’s assume that you have created simple module. Now, You can add this below code in your file at app/code/RH/Helloworld/Controller/Index/Index.php to reindex programmatically :
<?php
/**
* Created By : Rohan Hapani
*/
namespace RH\Helloworld\Controller\Index;
use Magento\Indexer\Model\IndexerFactory;
use Magento\Indexer\Model\Indexer\Collection;
class Index extends \Magento\Framework\App\Action\Action
{
/**
* @var IndexerFactory
*/
private $indexFactory;
/**
* @var Collection
*/
private $indexCollection;
/**
* @param \Magento\Framework\App\Action\Context $context
* @param IndexerFactory $indexFactory
* @param Collection $indexCollection
*/
public function __construct(
\Magento\Framework\App\Action\Context $context,
IndexerFactory $indexFactory,
Collection $indexCollection
) {
$this->indexCollection = $indexCollection;
$this->indexFactory = $indexFactory;
parent::__construct($context);
}
public function execute()
{
$indexes = $this->indexCollection->getAllIds();
foreach ($indexes as $index){
$indexFactory = $this->indexFactory->create()->load($index);
$indexFactory->reindexAll($index);
$indexFactory->reindexRow($index);
}
}
}
You can see that your all indexer successfully reindex. If you want to reindexing on condition base then, you can modify this above code and add your conditional base code inside that code.
That’s it !!!
I hope this blog is easy to understand about how to reindexing programmatically in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution.
Keep liking and sharing !!