Skip to main content
1 of 4
mendz
  • 153
  • 1
  • 8

add products to cart using \Magento\Quote\Api\CartRepositoryInterface

im trying to add to products to cart programatically using \Magento\Quote\Api\CartRepositoryInterface since \Magento\Checkout\Model\Cart is already deprecated. my code is successfully being inserted in quot, quote_item table and other tables. but its not creating any entries in quote_id_mask table. i dont know whats lacking in my code.

not also sure if its the problem thats causing the product to not appear in the front end.

public function __construct(
    Context $context,
    \Magento\Checkout\Model\CartFactory $cartFactory,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
    \Magento\Quote\Model\QuoteFactory $quoteFactory,
    \Magento\Quote\Model\Quote\ItemFactory $quoteItemFactory,
    \Magento\Quote\Api\Data\CartInterfaceFactory $cartInterface,
    \Magento\Quote\Api\CartRepositoryInterface $cartRepositoryInterface,
    \Magento\Quote\Api\Data\CartItemInterfaceFactory $cartItemInterface,
    \Magento\Store\Model\StoreManagerInterface $storeManagerInterface,
    \Magento\Framework\HTTP\PhpEnvironment\RemoteAddress $remoteAddress
){
    parent::__construct($context);
    $this->cartFactory = $cartFactory;
    $this->productRepository = $productRepository;
    $this->quoteFactory = $quoteFactory;
    $this->quoteItemFactory = $quoteItemFactory;
    $this->cartInterface = $cartInterface;
    $this->cartRepositoryInterface = $cartRepositoryInterface;
    $this->cartItemInterface = $cartItemInterface;
    $this->storeManagerInterface = $storeManagerInterface;
    $this->remoteAddress = $remoteAddress;
}

public function execute()
{
    $request_data = [
        ['sku' => 'product-sku', 'type' => 'sample']
    ];

    $cart = $this->cartInterface->create();
    foreach($request_data as $request){
        $product = $this->productRepository->get($request['sku']);

        $item = $this->cartItemInterface->create();
        $item->setProduct($product);
        $item->setQty(1);

        $cart->addItem($item);
        $cart->setStoreId($this->storeManagerInterface->getStore()->getId());
        $cart->setRemoteIp($this->remoteAddress->getRemoteAddress());

        $this->cartRepositoryInterface->save($cart);
    }

    die('test');
}
mendz
  • 153
  • 1
  • 8