Magento – Magento2:Get Cart item last added product after adding product to cart

cartfrontendmagento2

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.

Best Answer

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;

    }
}