How can I get the last date that a customer has purchased a product?

Thank you


Use this code to get customer's last order and then any order info:

use Magento\Sales\Model\OrderRepository;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Api\SortOrderBuilder;

public function __construct(
    OrderRepository $orderRepository,
    SearchCriteriaBuilder $searchCriteriaBuilder,
    FilterBuilder $filterBuilder,
    SortOrderBuilder $sortOrderBuilder
) {
    $this->orderRepository = $orderRepository;
    $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    $this->filterBuilder = $filterBuilder;
    $this->sortOrderBuilder = $sortOrderBuilder;

 * @param int $customerId
 * @return OrderSearchResultInterface
public function getCustomerOrders(int $customerId): OrderSearchResultInterface
    $this->searchCriteriaBuilder->addFilter(OrderInterface::CUSTOMER_ID, $customerId);
    $this->searchCriteriaBuilder->addFilter(OrderInterface::STATUS, ['canceled', 'holded'], 'nin');
    $searchCriteria = $this->searchCriteriaBuilder->create();
    $searchResults = $this->orderRepository->getList($searchCriteria);

    return $searchResults;

public function getLastOrder()
    $result = null;
    $searchResults = $this->getCustomerOrders(<customer_id_here>);

    if ($searchResults->getTotalCount() > 0) {
        $orders = $searchResults->getList();
        /** @var \Magento\Sales\Model\Order $lastOrder */
        $lastOrder = reset($orders);
        $result = $lastOrder;
    return $result;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.