Question

Is their any way we can get total amount that has been spend by customer in magento 2 ?

Was it helpful?

Solution

You can load the order collection for example by customer email, then loop through the orders totalling the value:

use Magento\Sales\Model\ResourceModel\Order\CollectionFactory;

    public function __construct(
        CollectionFactory $orderCollectionFactory
    ) {
       $this->orderCollectionFactory = $orderCollectionFactory;
    }

    public function test()
    {
        
        $customerEmail="testcustomer@mycoolshop.com";
        $total=0;
        $orders = $this->orderCollectionFactory->create()
            ->addAttributeToFilter('customer_email', $customerEmail);
        foreach ($orders as $order) {
            echo "Order# {$order->getIncrementId()} - Creation Date: {$order->getCreatedAt()} - Value: {$order->getGrandTotal()}". PHP_EOL;
            $total=$total+$order->getGrandTotal();
        }
        echo "Total for customer:".$total.PHP_EOL;


    }

OTHER TIPS

Please add below code in any root file. Please create custom.php file in root of magento folder and check your output.

<?php
ini_set('display_errors', 1);
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';

$bootstrap = Bootstrap::create(BP, $_SERVER);
$objectManager = $bootstrap->getObjectManager();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$OrderFactory = $objectManager->create('Magento\Sales\Model\ResourceModel\Order\CollectionFactory');
$orderCollection = $OrderFactory->create()->addFieldToSelect(array('*'));
$orderCollection->addAttributeToFilter('customer_email', 'test@zealousweb.com');

$total = 0;
foreach($orderCollection as $orderData)
{
     $total = $total + $orderData->getGrandTotal();
}   

echo $total;
die();
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top