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.
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.
ProductRepositoryInterfaceis 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 !!
14 comments
We have created a ticket on your behalf and soon you will get a resolution to your queries over that.
Ticket URL – https://webkul.uvdesk.com/en/customer/ticket/view/576887
Thanks and Regards,
Team Webkul
$resultPage = $this->resultPageFactory->create();
$params = array(
‘form_key’ => $this->formKey->getFormKey(),
‘product’ =>7617,//product Id
‘qty’ =>1,//quantity of product
‘price’ =>100, //product price
‘options’ => array(
1 => 100,
2 => 100
)
);
Will try to add next blog for the solution. Thanks
Hello,
To add multi products in cart, you can use below given code:
$productIdArray = [1,2,3];
$cart = $this->_cartModel;$storeId = $this->storeManager->getStore()->getId();foreach ($productIdsArray as $key => $productId) { $params = [ ‘form_key’ => $this->formKey->getFormKey(), ‘product’ => $productId,//product Id ‘qty’ =>1,//quantity of product ‘price’ =>100, //product price ]; try { $request = new MagentoFrameworkDataObject(); $request->setData($params); $productAddToCart = $this->productRepository->getById($productId, false, $storeId, true); $cart->addProduct($productAddToCart, $request); $this->messageManager->addSuccess(__(‘%1 is added in your cart’,$productAddToCart->getName())); } catch (Exception $e) { $this->messageManager->addError(__($e->getMessage())); }}$cart->save();
Here,
_cartModel is an instance of MagentoCheckoutModelCart;
storeManager is an instance of MagentoStoreModelStoreManagerInterface;
formKey is an instance of MagentoFrameworkDataFormFormKey;
productRepository is an instance of MagentoCatalogModelProductRepository;
After this all the products will be added in cart.
Bulbul AgarwalSoftware engineer (Magento)
Webkul Software Pvt. Ltd. Contact : India (+91)-9650486699 USA (+1)-9143531684
A 67 Sector 63 ,
Noida-201301 (U.P.)
India
http://webkul.com
This email and any files transmitted with it are confidential and contain privileged or copyright information. If you are not the intended recipient you must not disseminate, copy, distribute, or use this email or the information contained in it for any purpose other than to notify us. If you have received this message in error, please notify the sender immediately, and delete this email from your system.
Hello,
Hope this will help you.
Thank you.
let me check it works or not.
$this->_cart->addProductsByIds($products);
That’s it. Just pass the array of product Ids {$products}
where $this->_cart is instance of \Magento\Checkout\Model\Cart
Thanks,
Shubham
I am trying to add a product to cart when “checkout_cart_product_add_after” is fired. I have created an observer and have used your code for this. My code is as below:
formKey = $formKey;
$this->resultPageFactory = $resultPageFactory;
}
public function execute(MagentoFrameworkEventObserver $observer)
{
$resultPage = $this->resultPageFactory->create();
$params = array(
‘form_key’ => $this->formKey->getFormKey(),
‘product’ =>2056,//product Id
‘qty’ =>1,//quantity of product
);
$this->_redirect(“checkout/cart/add/form_key/”, $params);
return $resultPage;
}
}
However, this code is not working. Could you please check if this is the right way to write it?
you can use $this->_response->setRedirect($url)->sendResponse();
here, _response in the object of “MagentoFrameworkAppResponseInterface”
and $url is the url(string) on which you want to redirect (here, it should be cart url with the parameters).