We have a requirement that we wants to add product to cart programmatically in magento2.


1 Answer 1

protected $formKey;   
protected $cart;
protected $product;

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Data\Form\FormKey $formKey,
\Magento\Checkout\Model\Cart $cart,
\Magento\Catalog\Model\Product $product,
array $data = []) {
    $this->formKey = $formKey;
    $this->cart = $cart;
    $this->product = $product;      

public function execute()
  $productId =10;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, //product Id
                'qty'   =>1 //quantity of product                
    //Load the product based on productID   
    $_product = $this->product->load($productId);       
    $this->cart->addProduct($_product, $params);
  • Do we need to pass the customer id here?
    – srg
    Commented Aug 24, 2017 at 4:55
  • no need @srg please place the 'code' in your custom controller and submit the form Commented Aug 24, 2017 at 4:57
  • 1
    so how can we identify the product is added to which customer cart?
    – srg
    Commented Aug 24, 2017 at 4:58
  • ok let me check and update you, before that please try with the above code and comment me with u required details Commented Aug 24, 2017 at 5:02
  • 2
    the above code is adding product to guest cart succesfully. can you help me to add product to a registered customer cart using customer id or something like that?
    – srg
    Commented Aug 24, 2017 at 5:23

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