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 ?

  • 1
    Please review link – Purushotam Sharma Oct 10 '17 at 7:27
  • @PurushotamSharma thanks but in this link product adding to current cart ... i want load custom card by customer id – gh darvishani Oct 10 '17 at 7:33

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()) {

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


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);
        } catch (\Exception $e) { }

Hope this help !!

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.