You can get the invoice data for the specific order by order id in Magento 2.
Using Magento\Sales\Api\InvoiceRepositoryInterface interface, you need to use getList() function to fetch no. of invoice by sales order id.
Using SearchCriteriaBuilder Class, You need to filter by order id and pass search criteria object to getList() method of InvoiceRepositoryInterface.
<?php
namespace Path\To\Class;
use Exception;
use Psr\Log\LoggerInterface;
use Magento\Sales\Api\Data\InvoiceInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Sales\Api\InvoiceRepositoryInterface;
class InvoiceData
{
/**
* @var InvoiceRepositoryInterface
*/
private $invoiceRepository;
/**
* @var SearchCriteriaBuilder
*/
protected $searchCriteriaBuilder;
/**
* @var LoggerInterface
*/
private $logger;
public function __construct(
InvoiceRepositoryInterface $invoiceRepository,
SearchCriteriaBuilder $searchCriteriaBuilder,
LoggerInterface $logger
) {
$this->invoiceRepository = $invoiceRepository;
$this->searchCriteriaBuilder = $searchCriteriaBuilder;
$this->logger = $logger;
}
/**
* Get Invoice data by Order Id
*
* @param int $orderId
* @return InvoiceInterface[]|null
*/
public function getInvoiceDataByOrderId(int $orderId)
{
$searchCriteria = $this->searchCriteriaBuilder
->addFilter('order_id', $orderId)->create();
try {
$invoices = $this->invoiceRepository->getList($searchCriteria);
$invoiceRecords = $invoices->getItems();
} catch (Exception $exception) {
$this->logger->critical($exception->getMessage());
$invoiceRecords = null;
}
return $invoiceRecords;
}
}
on template
$orderId = (int)1; // order id $invoices = $this->getInvoiceDataByOrderId($orderId); foreach ($invoices as $invoice) { # code... var_dump($invoice); }