0

I need to implement a link which redirects to the url of the last order of the current user

How do I do that ?

I have a code that load the last order, but I need to get the URL

        $orders = $this->_orderCollectionFactory->create();
        $orders->addFieldToFilter('customer_id', $customerId);
        $orders->addOrder('customer_id');
        $orderId = $orders->getLastItem()->getData('entity_id');
        $objectManager =  \Magento\Framework\App\ObjectManager::getInstance();
        $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
2
  • Do you want this for logged in customers? Oct 8, 2018 at 12:12
  • Yes, for the current logged user Oct 8, 2018 at 12:17

2 Answers 2

1

Try the below code:

$orders = $this->_orderCollectionFactory->create();
$orders->addFieldToFilter('customer_id', $customerId);
$orders->addOrder('customer_id');
$orderId = $orders->getLastItem()->getData('entity_id');
$url = $block->getUrl('sales/order/view', ['order_id' => $orderId]);

And use this in phtml like below:

<a href="<?php echo $url; ?>">View Last Order</a>
9
  • Is this going to work with ease logged in user ? Oct 8, 2018 at 12:19
  • This will only work for logged in users. Because how do you get customer id without logged in? Does you code returns the last order of that customer? Oct 8, 2018 at 12:20
  • Sorry, maybe I'm not clear. Is this going to work if I'm using another user (last order of user 1 : 123, last user of user 2 : 97). If i'm with user 2, will I get the ID 97 ? Oct 8, 2018 at 12:22
  • Check mu updated answer. This will return exactly what you need. You only need to replace the your-customer-id with your current customer id. Oct 8, 2018 at 12:24
  • With your updated answer, there no order_id (but there was one before you changed your answer) Oct 8, 2018 at 12:30
0

You can get the order url as given below.

$this->getUrl('sales/order/view', ['order_id' => $order->getId()]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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