Magento 2.1.8 – Programmatically Update Cart Item Quantity

cartmagento-2.1.8magento2

Below is my code:

namespace Ves\Productlist\Controller\Cart;
use Magento\Quote\Model\QuoteRepository;
class CartUpdate extends \Magento\Framework\App\Action\Action
{
    protected $quoteRepository;

    public function __construct(
    \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
    ) {
    $this->quoteRepository = $quoteRepository;
    }

    public function execute()
    {
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
echo $cartId=$cart->getQuote()->getId();

    $itemId = 720;
    $itemQty = 1;

    $quote = $this->quoteRepository->getActive($cartId);
    $cartitems->setquoteId($cartId);
    $cartitems->setitemId($itemId);
    $cartitems->setqty($itemQty);

    $quoteItems[] = $cartitems;
    $quote->setItems($quoteItems);
    $this->quoteRepository->save($quote);
    $quote->collectTotals();

    }

}

But I am getting the below error:
enter link description here

Best Answer

Change Your construct as per below code :

namespace Ves\Productlist\Controller\Cart;

use Magento\Quote\Model\QuoteRepository;

class CartUpdate extends \Magento\Framework\App\Action\Action
{
    protected $quoteRepository;


    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
    ) {
        $this->quoteRepository = $quoteRepository;
        parent::__construct($context);
    }

    public function execute()
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $cart = $objectManager->get('\Magento\Checkout\Model\Cart'); 
        echo $cartId=$cart->getQuote()->getId();

        $itemId = 720;
        $itemQty = 1;

        $quote = $this->quoteRepository->getActive($cartId);
        $cartitems = $cart->getQuote()->getAllItems();
        $cartitems->setquoteId($cartId);
        $cartitems->setitemId($itemId);
        $cartitems->setqty($itemQty);

        $quoteItems[] = $cartitems;
        $quote->setItems($quoteItems);
        $this->quoteRepository->save($quote);
        $quote->collectTotals();

    }

}

After changing your code go to terminal and fire the below command.

cd /yourMagentoPath
php bin/magento setup:di:compile
Related Topic