Magento 2 – How to Remove Specific Product from Quote

cartmagento2quote

I set product's expire time in my custom module. When, product is expire at that time that specific product should be remove from quote. I used event layout_load_before for that.

Because, this code should be working from any page in whole site. If, any other event should i should then, please inform me that also.

Actual Result :

Now, point is that if I remove specific product from quote. Then, product will be remove but minicart is not update.

Expected Result :

When product remove from cart/quote then minicart also refresh and product should be remove from quote/cart.

How to do that ? Please help me.

My observer code :

$items = $this->_checkoutSession->getQuote()->getAllItems();
$createdAt = $this->_stdTimezone->date()->format('Y-m-d H:i:s');
foreach ($items as $key => $item) {
    if (strtotime($customModel->getExpireTime()) <= strtotime($createdAt)) {
        $this->_cart->removeItem($item->getId());
    }
}
$this->_cart->save();

Best Answer

You need to inject \Magento\Quote\Model\Quote\Item class in your construct as like below way :

/**
 * @var \Magento\Quote\Model\Quote\Item
 */
protected $_itemModel;
/**
 * Add constructor.
 * @param \Magento\Quote\Model\Quote\Item $itemModel
 */
public function __construct(
    .........
    \Magento\Quote\Model\Quote\Item $itemModel
    .........
) {
    .........
    $this->_itemModel = $itemModel;
    .........
}

Add this below code in your function

$items = $this->_checkoutSession->getQuote()->getAllItems();
$createdAt = $this->_stdTimezone->date()->format('Y-m-d H:i:s');
foreach ($items as $key => $item) {
    if (strtotime($customModel->getExpireTime()) <= strtotime($createdAt)) {
        $this->_itemModel->load($item->getItemId())->delete();
    }
}
$this->_cart->save();

Remove generation/generated folder and clean cache.