1

I want to add a product to customer cart by product id and customer id

I think that way should be like this

load quote session and set customer id and then add product .

can you help me to do this ?

gh darvishani
  • 855
  • 1
  • 9
  • 37

1 Answers1

6

Use below code to add product into cart using customer Id and Product Id

public function __construct(
    /* Add below dependencies */
    \Magento\Store\Model\StoreManagerInterface $storeManager,
    \Magento\Customer\Api\CustomerRepositoryInterface $customerRepositoryInterface,
    \Magento\Quote\Model\Quote $quoteModel,
    \Magento\Catalog\Api\ProductRepositoryInterface $productRepository
) {
    $this->storeManager                 = $storeManager;
    $this->_customerRepositoryInterface = $customerRepositoryInterface;
    $this->quoteModel                   = $quoteModel;
    $this->productRepository            = $productRepository;
}

Add below code in your existing function:

try {
    $customer = $this->_customerRepositoryInterface->getById($customerId);
    $quote    = $this->quoteModel->loadByCustomer($customer);
    if (!$quote->getId()) {
        $quote->setCustomer($customer);
        $quote->setIsActive(1);
        $quote->setStoreId($this->storeManager->getStore()->getId());
    }


    $product = $this->productRepository->getById($productId);
    $quote->addProduct($product, $qty);
    $quote->collectTotals()->save();
} catch (\Exception $e) {
    //echo $e->getMessage(); die;
}

Updated

For adding the multiple products into cart, You can use like below where $products is array of product Ids.

foreach ($products as $productId) {
    $product = $this->productRepository->getById($productId);
    if ($product->getId() && $product->isVisibleInCatalog()) {
        try {
            $request = new \Magento\Framework\DataObject(['qty' => 1]);
            $quote->addProduct($product, $request);
            $count++;
        } catch (\Exception $e) { }
    }
}
$quote->collectTotals()->save();

Hope this help !!

Pankaj Pareek
  • 3,556
  • 3
  • 23
  • 46