Get Customer Order collection using Magento 2 Programmatically is a simple task using creating a single Block class in the module.
Customer has multiple orders and we have requirement like gather all the customer orders for a site, in this case this article is used.
The customer id is required to fetch the customer placed Order collection in Magento 2.
Get Customer Order collection, We have to create a factory object of Magento\Sales\Model\ResourceModel\Order\Collection class.
Instantiate the Factory object to the __consturct() method and apply condition with customer id.
<?php namespace Jesadiya\CustomerPlacedOrder\Block; use Magento\Framework\View\Element\Template; use Magento\Framework\View\Element\Template\Context; use Magento\Sales\Model\ResourceModel\Order\CollectionFactory; class CustomerOrder extends Template { /** * @var array */ private $data; /** * @var Context */ private $context; /** * @var CollectionFactory */ private $orderCollectionFactory; public function __construct( Context $context, CollectionFactory $orderCollectionFactory, array $data = [] ) { $this->orderCollectionFactory = $orderCollectionFactory; $this->logger = $logger; parent::__construct($context, $data); } /** * @return array */ public function getCustomerOrder() { $customerId = 2; // pass customer id $customerOrder = $this->orderCollectionFactory->create() ->addFieldToFilter('customer_id', $customerId); return $customerOrder->getData(); } }
Using the above Block class, We have defined a method to fetch customer order by its id. Pass Dynamic Customer id to fetch record of Customer Order.
Call method $this->getCustomerOrder() with iterate over the loop the fetch customer placed order in Magento 2.
Using the loop, Each order will be display with its full details.