Magneto 2 Add product to cart programmatically


Magneto 2 Add product to cart programmatically- We sometimes need to add products to shopping cart using custom code. Here in this article, we are going to explain how you can add products in cart using Magento\Checkout\Model\Cart class.


Magneto 2 Add product to cart programmatically Example

You can add product to cart using factory method & cart session object.

Magneto 2 Add product to cart programmatically

Factory Method

Using factory method you can add product to cart using product id simply as below-

Magneto 2 Add product to cart programmatically:


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->product = $product; 
    $this->cart = $cart;     
    parent::__construct($context);
}

public function execute()
 { 
  $productId =189;
  $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId,
                'qty'   =>1 //quantity to add             
            );              
    //Load the product based on productID   
    $product = $this->product->load($productId);       
    $this->cart->addProduct($product, $params);
    $this->cart->save();
 }



Advertisements

Add Comment

📖 Read More