How to get Invoice comments list programmatically in Magento 2?

Today, I am going to explain to you how you can show/get the order comments list on the invoice for Magento 2. Invoice comments can be added by the store admin from the Magento backend for the invoice query. Admin can notify about the comments to the customers by email. Admin can view that order comments of customers from the order view page. But there is no option to show those comments in the invoice generated in the back-end.

Magento\Sales\Api\InvoiceManagementInterface is the class that is responsible to fetch a list of comments from the invoice.

 

<?php
namespace [VendorName]\[ModuleName]\Model;

use Exception;
use Magento\Sales\Api\InvoiceManagementInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Sales\Api\Data\InvoiceCommentSearchResultInterface;

class Comments
{
    /**
     * @var InvoiceManagementInterface
     */
    private $invoiceService;

    public function __construct(
        InvoiceManagementInterface $invoiceService
    ) {
        $this->invoiceService = $invoiceService;
    }

    /**
     * @param int $invoiceId
     * @return InvoiceCommentSearchResultInterface
     */
    public function getComments($invoiceId): ?InvoiceCommentSearchResultInterface
    {
    	$invoiceComments = null;
        try {
            $invoiceComments = $this->invoiceService->getCommentsList($invoiceId);
        } catch (NoSuchEntityException $exception) {
            throw new Exception($exception->getMessage());
        }
        return $invoiceComments;
    }
}

Call method with a required parameter, Be careful to assign Invoice Id, not the order id. Verify Invoice has Comments available or not by the getTotalCount().

$invoiceId = 1; // Invoice id
$invoiceComments = $this->getComments($invoiceId);
if ($invoiceComments->getTotalCount()) {
	foreach($invoiceComment as $comment) {
        echo "<pre>";print_r($comment->debug());
    }
}

 

And it is done. If the Invoice contains the Comments, the response will be an array of comments otherwise value will be null.

If you like this article, then share this with your Magneto friends and colleagues. Also, let us know the thoughts in the comments below. If something goes wrong while implementing the codes, then you can contact us at any time, and we will be happy to help you.