Menu

Tuesday, November 9, 2021

How to Get Customer Order Collection by Customer Id in Magento 2

In this article, I am going to explain how to get customer order collection by customer id in Magento 2.


Using the below code you can get customer order data bypassing customer id.


Using Dependency Injection

protected $_orderCollectionFactory;
public function __construct(
    \Magento\Framework\View\Element\Template\Context $context,
    \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory,
    array $data = []
) {
    $this->_orderCollectionFactory = $orderCollectionFactory;
    parent::__construct($context, $data);
}
 
public function getCustomerOrderCollection($customerId) 
{
    $collection = array();
    if($customerId > ) {
        $collection = $this->_orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId);
    }
    return $collection;
}

Add the below code in a template file.

// Customer Id
$customerId = 1;
$orders = $block->getCustomerOrderCollection($customerId);
//print all orders
echo "<pre>";
print_r($orders->getData());
echo "</pre>";
foreach ($orders as $order) {
    $orderId = $order->getId();
    $subtotal = $order->getSubtotal();
}


Using Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerId = 1;
$orderCollectionFactory = $objectManager->get('Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$orders = $orderCollectionFactory->create()->addFieldToFilter('customer_id', $customerId);
//print all orders
echo "<pre>";
print_r($orders->getData());
echo "</pre>";
foreach ($orders as $order) {
    $orderId = $order->getId();
    $subtotal = $order->getSubtotal();
}