I'm trying to add products to cart programmatically using \Magento\Quote\Api\CartRepositoryInterface since \Magento\Checkout\Model\Cart is already deprecated. My code is successfully being inserted in quote, quote_item table and other tables. but it's not creating any entries in quote_id_mask table. I don't know what's lacking in my code.
Not also sure if it's the problem that's 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();
$cart->setStoreId($this->storeManagerInterface->getStore()->getId());
$cart->setRemoteIp($this->remoteAddress->getRemoteAddress());
foreach($request_data as $request){
$product = $this->productRepository->get($request['sku']);
$item = $this->cartItemInterface->create();
$item->setProduct($product);
$item->setQty(1);
$cart->addItem($item);
$this->cartRepositoryInterface->save($cart);
}
die('test');
}