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
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;
}
}
-
-
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.– rou6eCommented Jun 11, 2021 at 13:01
-
Can you tell us where you added this code snippet? Did you create a new module? Commented Sep 1, 2023 at 9:55