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.

1 Answer 1

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;

    }
}
3
  • Thank You ,, It's Working :)
    – Bhavesh
    Mar 2, 2020 at 8:38
  • It seems (at least on my m2 instance) that it will work only if you need to check literally "what is the last product reference added in the cart", not considering qty. If you add "Product A", then "Product B", then "Product A" again, $lastAddedProductName would be "Product B". To get the product related to the last add_to_cart action, you should consider sorting the product list by "updated_at" attribute.
    – rou6e
    Jun 11, 2021 at 13:01
  • Can you tell us where you added this code snippet? Did you create a new module?
    – TheFrakes
    Sep 1, 2023 at 9:55

Your Answer

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

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