Back to Top

How to create product review & rating programatically in Magento2

Updated 22 March 2024

Here, I am going to explain that how to create product review & rating programatically.

Sometimes we have to create product through any external medium. For an example csv import, any other website etc.

Product review also necessary details for any product. You can create product review to use following code.

<?php

namespace Test\Module\Controller\Review;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;

class Testreview extends Action
{
    public function __construct(
        Context $context,
        \Magento\Review\Model\ReviewFactory $reviewFactory,
        \Magento\Review\Model\RatingFactory $ratingFactory,
        \Magento\Store\Model\StoreManagerInterface $storeManager
    ) {
        parent::__construct($context);
        $this->_reviewFactory = $reviewFactory;
        $this->_ratingFactory = $ratingFactory;
        $this->_storeManager = $storeManager;
    }

    public function execute()
    {
        $productId = 2047;//product id you set accordingly
        $reviewFinalData['ratings'][1] = 5;
        $reviewFinalData['ratings'][2] = 5;
        $reviewFinalData['ratings'][3] = 5;
        $reviewFinalData['nickname'] = "John Doe";
        $reviewFinalData['title'] = "Create Review Programatically";
        $reviewFinalData['detail'] = "This is nice blog for magento 2.Creating product reviews programatically.";
        $review = $this->_reviewFactory->create()->setData($reviewFinalData);
        $review->unsetData('review_id');
        $review->setEntityId($review->getEntityIdByCode(\Magento\Review\Model\Review::ENTITY_PRODUCT_CODE))
            ->setEntityPkValue($productId)
            ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED)//By default set approved
            ->setStoreId($this->_storeManager->getStore()->getId())
            ->setStores([$this->_storeManager->getStore()->getId()])
            ->save();

        foreach ($reviewFinalData['ratings'] as $ratingId => $optionId) {
            $this->_ratingFactory->create()
                ->setRatingId($ratingId)
                ->setReviewId($review->getId())
                ->addOptionVote($optionId, $productId);
        }

        $review->aggregate();
    }
}

I have added this code in controller file. You can add this accordingly to test it.

programatically reivew created

After run this code. You can see the review at the product view page also you can check admin panel.

Searching for an experienced
Magento 2 Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home