How to add product to cart by product id and customer id?

The question:

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 ?

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

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

public function __construct(
    /* Add below dependencies */
    MagentoStoreModelStoreManagerInterface $storeManager,
    MagentoCustomerApiCustomerRepositoryInterface $customerRepositoryInterface,
    MagentoQuoteModelQuote $quoteModel,
    MagentoCatalogApiProductRepositoryInterface $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 MagentoFrameworkDataObject(['qty' => 1]);
            $quote->addProduct($product, $request);
            $count++;
        } catch (Exception $e) { }
    }
}
$quote->collectTotals()->save();

Hope this help !!


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment