How to add Product to store cart Programmatically in Magento 2

How to add Product to store cart Programmatically in Magento 2

Magento is powerful enough to handle small business as well as large retail stores like Hermes, Paul Smith, Ford, Nike etc. But at behind it takes huge efforts of the store owner to maintain products and run a successful e-commerce store. And we developers are born to drink coffee and to simplify the daily routine task of store owners so they can utilize this time to focus on other factors of the store.
Recently one of our clients was asking us about a script where he wants to add products to cart programmatically to save his time and efforts. Actually, that script is pretty useful to everyone so we decided to share the script on our MageComp blog.

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;  	
	parent::__construct($context);
}
 
public function execute()
 {
  $productId =10;     // Your Product Id
  $params = array(
            	'form_key' => $this->formKey->getFormKey(),
            	'product' => $productId,             	
             'qty'   =>1     //quantity of product            	
        	); 
         	
	//Load the product based on productID  
	$_product = $this->product->load($productId);   	
	$this->cart->addProduct($_product, $params);
	$this->cart->save();

You can even use or customize this code as per your need to add more additional or custom options as well as configurable product code.
Hope you liked this tiny little solution. Don’t forget to smash that down stars and comment down below if you face any issue while implementing this code.
Happy Coding!

Previous Article

How to Set Product Tier Price Programmatically in Magento 2

Next Article

How to override contact form in Magento 2 theme

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨