Magento 2

How to Programmatically Add Product to Cart in Magento 2

Magento 2

How to Programmatically Add Product to Cart in Magento 2

There are many uses of add to cart functionality; for example, the admin may require to add a product to cart whenever a particular product is added to the cart by a customer, the admin may want to give away the free product by default. So you can use below code for this functionality.


<?php
namespace Vendor\Extension\Controller\Index;
use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Framework\Data\Form\FormKey;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Model\Product;
class CustomController extends Action
{
    protected $formKey;   
    protected $cart;
    protected $product;
    public function __construct(
        Context $context,
        FormKey $formKey,
        Cart $cart,
        Product $product) {
            $this->formKey = $formKey;
            $this->cart = $cart;
            $this->product = $product;      
            parent::__construct($context);
    }
    public function execute()
     { 
        $productId =100;
        $params = array(
                    'form_key' => $this->formKey->getFormKey(),
                    'product' => $productId, 
                    'qty'   =>1
                );              
        $product = $this->product->load($productId);       
        $this->cart->addProduct($product, $params);
        $this->cart->save();
     }
}

Add above code in your module and task is done.

Thanks.