How can I get the last date that a customer has purchased a product?
Thank you
Hello @blaz_p
You can fetch sales order collection with customer filter:
<?phpnamespace 'YOUR_CUSTOM_NAME_SPACE'; class YOURCALSS extends \Magento\Framework\App\Action\Action{ protected $_orderCollectionFactory; public function __construct( Magento\Framework\App\Action\Context $context, \Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollectionFactory ) { $this->_orderCollectionFactory = $orderCollectionFactory; parent::__construct($context); } } public function YOURFUNCTION() { $collection = $this->_orderCollectionFactory->create()->addAttributeToSelect('*'); // You Can filter collection as $this->orderCollectionFactory->addFieldToFilter($field, $condition); } } }
->addAttributeToFilter('customer_id', $customer_id) //fetch order in desc order and get first order item's as last purchase item
Is there any REST api in magento 2.2 version to get last purchase date of a customer?
@blaz_p
You can use below code for getting last date of purchase of any customer,
<?php
namespace NameSpace;
class CLASSNAME extends \Magento\Framework\App\Action\Action
{
public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Sales\Model\ResourceModel\Order\CollectionFactory $orderCollection
) {
$this->_orderCollection = $orderCollection;
parent::__construct($context);
}
public function execute()
{
$customer_id = 1; //set customer id whose last order you want to get
$last_order = $this->_orderCollection->create()->addFieldToFilter('customer_id',$customer_id)
->setOrder('created_at', 'DESC')
->getFirstItem();
echo $last_date = $last_order->getCreatedAt();die;
}
}If my answer is useful click kudos and Accept as Solution
You can first use customer auth api:
http://your_site_url/index.php/rest/V1/integration/customer/token
Then get all orders of customer,last order created_at is the last date of purchase of any customer.
"http://127.0.0.1/mago/index.php/rest/V1/orders?searchCriteria=all"If my answer is useful click kudos and Accept as Solution
Thanks @verma_mallika.
I understand we can get purchase date using V1/orders api by taking the last record.
My usecase required direct REST API where I could find information related to purchase data, eg. last purchase date, purchase frequency etc.
I went through all the swagger apis mentioned in 2.3 version. Looks like there are no such Apis.