Back to Top

How to Add Product in Cart in Magento 2

Updated 18 December 2025

Introduction

In Magento 2 development, there are many scenarios where adding a product to the cart using the default “Add to Cart” button is not enough.

Magento 2 provides a powerful cart and quote API that allows developers to add products to the cart from controllers, observers, cron jobs, or custom services.

Understanding this process is essential for building advanced Magento features while following best practices.

Custom requirements such as AJAX add-to-cart, bulk add, custom promotions, API-driven cart actions, or admin-triggered cart updates often require adding products to the cart programmatically.

In this blog, we’ll look at a simple controller-based approach to add a product to the cart programmatically in Magento 2.

Searching for an experienced
Magento 2 Company ?
Find out More

Create a Controller to Add Product to Cart

Below is a basic example of a frontend controller that adds a product to the cart using its product ID.

Controller File

Vendor/Module/Controller/Index/AddToCart.php

<?php
namespace Vendor\Module\Controller\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\App\Action\Context;
use Magento\Checkout\Model\Cart;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Exception\NoSuchEntityException;

class AddToCart extends Action
{
    protected $cart;
    protected $productRepository;

    public function __construct(
        Context $context,
        Cart $cart,
        ProductRepositoryInterface $productRepository
    ) {
        parent::__construct($context);
        $this->cart = $cart;
        $this->productRepository = $productRepository;
    }

    public function execute()
    {
        try {
            $productId = 1; // Product ID
            $qty = 1;       // Quantity

            $product = $this->productRepository->getById($productId);

            $params = [
                'product' => $productId,
                'qty' => $qty
            ];

            $this->cart->addProduct($product, $params);
            $this->cart->save();

            $this->messageManager->addSuccessMessage(__('Product added to cart successfully.'));
        } catch (NoSuchEntityException $e) {
            $this->messageManager->addErrorMessage(__('Product does not exist.'));
        } catch (\Exception $e) {
            $this->messageManager->addErrorMessage(__('Unable to add product to cart.'));
        }

        return $this->_redirect('checkout/cart');
    }
}

How This Works

  • The controller uses Magento’s Cart model to interact with the quote.
  • ProductRepositoryInterface is used to load the product safely.
  • addProduct() adds the product to the current cart session.
  • save() Persists the cart data.
  • Proper exception handling ensures stability.

Key Notes for Developers

  • For configurable or bundle products, you must pass selected options in $params.
  • For AJAX implementations, return a JSON response instead of redirecting.
  • Always validate product availability and stock before adding to the cart.
  • This logic can also be reused in observers, helpers, or service classes.

That is all for the dev doc article on Add Product Cart in Magento 2. Please reach out to our team via support ticket for any queries.

Also, make sure to view our complete range of Magento 2 extensions.

Happy Coding !!

. . .

Leave a Comment

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


14 comments

  • Amla
    • Vaibhav Arora (Moderator)
  • Ashish Sharma
    • Webkul Support
  • vivek singh
    • Webkul Support
      • Webkul Support
      • vivek singh
      • Shubham Mathur
  • nagaraju
  • Robar
  • DependencyHell
  • Magento Testing
    • Bulbul agarwal
  • Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home