Magento 2 – How to Get All Orders of Customer by Email ID

magento2magento2.2magento2.3order-emailsales-order

How can I get all orders of a customer via his/her email id who is logged in,
I am using current session to get user's email id

public function getCustomerData() {
    if ($this->_customerSession->isLoggedIn()) {
        return $this->_customerSession->getCustomerData();
    }
    return false;
}

In phtml

  $customerData = $block->getCustomerData();
  if($customerData) {
    echo 'Customer Email: ' . $customerData->getEmail() . '<br/>'; }

Earlier I was getting my orders information by order id

public function getOrderInformation($orderid)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $order = $objectManager->create('Magento\Sales\Api\OrderRepositoryInterface')->get($orderid);
    return $order;
}

How can I get all orders by customer email id

Best Answer

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();

//*****************loading Customer session *****************//
$customerSession = $objectManager->create('Magento\Customer\Model\Session');

//******** Checking whether customer is logged in or not ********//
if ($customerSession->isLoggedIn()) {
$customer_email = $customerSession->getCustomer()->getEmail();

// ***********Getting order collection using customer email id ***********//
 $order_collection = $objectManager->create('Magento\Sales\Model\Order')->getCollection()->addAttributeToFilter('customer_email', $customer_email);

 //echo "<pre>";print_r($order_collection->getData());
 foreach ($order_collection as $order){ 
    echo "Order Id: ".$order->getEntityId(); 
    echo "Customer Id: ".$order->getCustomerId(); 
   } 
}

Order collection based on logged in Customer Email Id (Customer All orders)

I hope this will help

Related Topic