1

I am using Magento2 I need get Cart item last added product after adding product to cart.If anyone idea reply me,How to achieve this my requirement.

4

Create after plugin for Magento\Checkout\Controller\Cart\Add.php

namespace Vendor\Module\Plugin;

class AddToCart
{
public function __construct(
       \Magento\Checkout\Model\Session  $checkoutSession
    ) {
       $this->checkoutSession = $checkoutSession;
    }

public function afterExecute(\Magento\Checkout\Controller\Cart\Add $subject, $result)
    {
        $items = $this->checkoutSession->getQuote()->getAllItems();
        $max = 0;
        $lastItem = null;
        foreach ($items as $item){
            if ($item->getId() > $max) {
                $max = $item->getId();
                $lastItem = $item;
            }
        }
        if ($lastItem){
            $lastAddedProductName = $lastItem->getName();
        }

        return $result;

    }
}
| improve this answer | |
  • Thank You ,, It's Working :) – Bhavesh Mar 2 at 8:38
0
use \Magento\Checkout\Model\Session as CheckoutSession;

    /** @var CheckoutSession */
    private $checkoutSession;

    /**
     * @param CheckoutSession $checkoutSession
     */
    public function __construct(CheckoutSession $checkoutSession)
    {
        $this->checkoutSession = $checkoutSession;
    }

Now you need to get quote from checkout session

    $quote = $this->checkoutSession->getQuote();
    $lastItem = $quote->getLastAddedItem();

Also, I am not sure in which place you need last added Item, If you want on add to cart observer then you need to use this code before adding product item to the cart otherwise it will overwrite the last added item

| improve this answer | |
  • Thanks for sharing your answer – Rv Singh Apr 18 '19 at 10:56
  • It is helping to you? – Keyur Shah Apr 18 '19 at 19:01
  • This method doesn't appear to exist: \Magento\Quote\Model\Quote:: getLastAddedItem() – versalle88 Jan 22 at 20:24

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.