{"id":43526,"date":"2016-03-18T13:01:06","date_gmt":"2016-03-18T13:01:06","guid":{"rendered":"http:\/\/webkul.com\/blog\/?p=43526"},"modified":"2025-12-18T09:04:21","modified_gmt":"2025-12-18T09:04:21","slug":"add-product-cart-magento2","status":"publish","type":"post","link":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/","title":{"rendered":"How to Add Product in Cart in Magento 2"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">Introduction<\/h2>\n\n\n\n<p>In <a href=\"https:\/\/webkul.com\/magento-development\/\">Magento 2 development<\/a>, there are many scenarios where adding a product to the cart using the default \u201cAdd to Cart\u201d button is not enough.<\/p>\n\n\n\n<p>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.<\/p>\n\n\n\n<p>Understanding this process is essential for building advanced Magento features while following best practices.<\/p>\n\n\n\n<p>Custom requirements such as <strong>AJAX add-to-cart<\/strong>, <strong>bulk add<\/strong>, <strong>custom promotions<\/strong>, <strong>API-driven cart actions<\/strong>, or <strong>admin-triggered cart updates<\/strong> often require adding products to the cart programmatically.<\/p>\n\n\n\n<p>In this blog, we\u2019ll look at a <strong>simple controller-based approach<\/strong> to add a product to the cart programmatically in Magento 2.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\">Create a Controller to Add Product to Cart<\/h2>\n\n\n\n<p>Below is a basic example of a frontend controller that adds a product to the cart using its <strong>product ID<\/strong>.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Controller File<\/h3>\n\n\n\n<p><code>Vendor\/Module\/Controller\/Index\/AddToCart.php<\/code><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\">&lt;?php\nnamespace Vendor\\Module\\Controller\\Index;\n\nuse Magento\\Framework\\App\\Action\\Action;\nuse Magento\\Framework\\App\\Action\\Context;\nuse Magento\\Checkout\\Model\\Cart;\nuse Magento\\Catalog\\Api\\ProductRepositoryInterface;\nuse Magento\\Framework\\Exception\\NoSuchEntityException;\n\nclass AddToCart extends Action\n{\n    protected $cart;\n    protected $productRepository;\n\n    public function __construct(\n        Context $context,\n        Cart $cart,\n        ProductRepositoryInterface $productRepository\n    ) {\n        parent::__construct($context);\n        $this-&gt;cart = $cart;\n        $this-&gt;productRepository = $productRepository;\n    }\n\n    public function execute()\n    {\n        try {\n            $productId = 1; \/\/ Product ID\n            $qty = 1;       \/\/ Quantity\n\n            $product = $this-&gt;productRepository-&gt;getById($productId);\n\n            $params = &#091;\n                &#039;product&#039; =&gt; $productId,\n                &#039;qty&#039; =&gt; $qty\n            ];\n\n            $this-&gt;cart-&gt;addProduct($product, $params);\n            $this-&gt;cart-&gt;save();\n\n            $this-&gt;messageManager-&gt;addSuccessMessage(__(&#039;Product added to cart successfully.&#039;));\n        } catch (NoSuchEntityException $e) {\n            $this-&gt;messageManager-&gt;addErrorMessage(__(&#039;Product does not exist.&#039;));\n        } catch (\\Exception $e) {\n            $this-&gt;messageManager-&gt;addErrorMessage(__(&#039;Unable to add product to cart.&#039;));\n        }\n\n        return $this-&gt;_redirect(&#039;checkout\/cart&#039;);\n    }\n}<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">How This Works<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The controller uses Magento\u2019s <strong>Cart model<\/strong> to interact with the quote.<\/li>\n\n\n\n<li><code>ProductRepositoryInterface<\/code> is used to load the product safely.<\/li>\n\n\n\n<li><code>addProduct()<\/code> adds the product to the current cart session.<\/li>\n\n\n\n<li><code>save()<\/code> Persists the cart data.<\/li>\n\n\n\n<li>Proper exception handling ensures stability.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\">Key Notes for Developers<\/h2>\n\n\n\n<ul class=\"wp-block-list\">\n<li>For <strong>configurable or bundle products<\/strong>, you must pass selected options in <code>$params<\/code>.<\/li>\n\n\n\n<li>For <strong>AJAX implementations<\/strong>, return a JSON response instead of redirecting.<\/li>\n\n\n\n<li>Always validate product availability and stock before adding to the cart.<\/li>\n\n\n\n<li>This logic can also be reused in <strong>observers, helpers, or service classes<\/strong>.<\/li>\n<\/ul>\n\n\n\n<p>That is all for the dev doc article on Add Product Cart in Magento 2. Please reach out to our team via <a href=\"https:\/\/webkul.uvdesk.com\/en\/customer\/create-ticket\/\" target=\"_blank\" rel=\"noopener\">support ticket<\/a> for any queries.<\/p>\n\n\n\n<p>Also, make sure to view our complete range of <a href=\"https:\/\/store.webkul.com\/Magento-2.html\" target=\"_blank\" rel=\"noopener\">Magento 2 extensions<\/a>.<\/p>\n\n\n\n<p>Happy Coding !!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction In Magento 2 development, there are many scenarios where adding a product to the cart using the default \u201cAdd to Cart\u201d 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 <a href=\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\">[&#8230;]<\/a><\/p>\n","protected":false},"author":68,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[302],"tags":[2070],"class_list":["post-43526","post","type-post","status-publish","format-standard","hentry","category-magento2","tag-magento2"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.5 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>How to Add Product Cart Magento 2 Programmatically<\/title>\n<meta name=\"description\" content=\"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"How to Add Product Cart Magento 2 Programmatically\" \/>\n<meta property=\"og:description\" content=\"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\" \/>\n<meta property=\"og:site_name\" content=\"Webkul Blog\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/webkul\/\" \/>\n<meta property=\"article:published_time\" content=\"2016-03-18T13:01:06+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-12-18T09:04:21+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-og.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"630\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Bulbul\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@webkul\" \/>\n<meta name=\"twitter:site\" content=\"@webkul\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Bulbul\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"2 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\"},\"author\":{\"name\":\"Bulbul\",\"@id\":\"https:\/\/webkul.com\/blog\/#\/schema\/person\/c9c6288b3950490ffdb37cb2a526996e\"},\"headline\":\"How to Add Product in Cart in Magento 2\",\"datePublished\":\"2016-03-18T13:01:06+00:00\",\"dateModified\":\"2025-12-18T09:04:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\"},\"wordCount\":274,\"commentCount\":14,\"publisher\":{\"@id\":\"https:\/\/webkul.com\/blog\/#organization\"},\"keywords\":[\"Magento2\"],\"articleSection\":[\"Magento2\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\",\"url\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\",\"name\":\"How to Add Product Cart Magento 2 Programmatically\",\"isPartOf\":{\"@id\":\"https:\/\/webkul.com\/blog\/#website\"},\"datePublished\":\"2016-03-18T13:01:06+00:00\",\"dateModified\":\"2025-12-18T09:04:21+00:00\",\"description\":\"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.\",\"breadcrumb\":{\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/webkul.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"How to Add Product in Cart in Magento 2\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/webkul.com\/blog\/#website\",\"url\":\"https:\/\/webkul.com\/blog\/\",\"name\":\"Webkul Blog\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/webkul.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/webkul.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/webkul.com\/blog\/#organization\",\"name\":\"WebKul Software Private Limited\",\"url\":\"https:\/\/webkul.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/webkul.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-logo-accent-sq.png\",\"contentUrl\":\"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-logo-accent-sq.png\",\"width\":380,\"height\":380,\"caption\":\"WebKul Software Private Limited\"},\"image\":{\"@id\":\"https:\/\/webkul.com\/blog\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/webkul\/\",\"https:\/\/x.com\/webkul\",\"https:\/\/www.instagram.com\/webkul\/\",\"https:\/\/www.linkedin.com\/company\/webkul\",\"https:\/\/www.youtube.com\/user\/webkul\/\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/webkul.com\/blog\/#\/schema\/person\/c9c6288b3950490ffdb37cb2a526996e\",\"name\":\"Bulbul\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/webkul.com\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/37ea7175f5ae6557d01bb38e147f6a02a540714ecdb71770d8ec554d4d34c23f?s=96&d=https%3A%2F%2Fcdnblog.webkul.com%2Fblog%2Fwp-content%2Fuploads%2F2019%2F10%2Feva.png&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/37ea7175f5ae6557d01bb38e147f6a02a540714ecdb71770d8ec554d4d34c23f?s=96&d=https%3A%2F%2Fcdnblog.webkul.com%2Fblog%2Fwp-content%2Fuploads%2F2019%2F10%2Feva.png&r=g\",\"caption\":\"Bulbul\"},\"url\":\"https:\/\/webkul.com\/blog\/author\/bulbul896\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"How to Add Product Cart Magento 2 Programmatically","description":"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/","og_locale":"en_US","og_type":"article","og_title":"How to Add Product Cart Magento 2 Programmatically","og_description":"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.","og_url":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/","og_site_name":"Webkul Blog","article_publisher":"https:\/\/www.facebook.com\/webkul\/","article_published_time":"2016-03-18T13:01:06+00:00","article_modified_time":"2025-12-18T09:04:21+00:00","og_image":[{"width":1200,"height":630,"url":"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-og.png","type":"image\/png"}],"author":"Bulbul","twitter_card":"summary_large_image","twitter_creator":"@webkul","twitter_site":"@webkul","twitter_misc":{"Written by":"Bulbul","Est. reading time":"2 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#article","isPartOf":{"@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/"},"author":{"name":"Bulbul","@id":"https:\/\/webkul.com\/blog\/#\/schema\/person\/c9c6288b3950490ffdb37cb2a526996e"},"headline":"How to Add Product in Cart in Magento 2","datePublished":"2016-03-18T13:01:06+00:00","dateModified":"2025-12-18T09:04:21+00:00","mainEntityOfPage":{"@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/"},"wordCount":274,"commentCount":14,"publisher":{"@id":"https:\/\/webkul.com\/blog\/#organization"},"keywords":["Magento2"],"articleSection":["Magento2"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/","url":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/","name":"How to Add Product Cart Magento 2 Programmatically","isPartOf":{"@id":"https:\/\/webkul.com\/blog\/#website"},"datePublished":"2016-03-18T13:01:06+00:00","dateModified":"2025-12-18T09:04:21+00:00","description":"How to add product cart in Magento 2 programmatically with a custom price. Read the complete dev doc to find the complete steps.","breadcrumb":{"@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/webkul.com\/blog\/add-product-cart-magento2\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/webkul.com\/blog\/add-product-cart-magento2\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/webkul.com\/blog\/"},{"@type":"ListItem","position":2,"name":"How to Add Product in Cart in Magento 2"}]},{"@type":"WebSite","@id":"https:\/\/webkul.com\/blog\/#website","url":"https:\/\/webkul.com\/blog\/","name":"Webkul Blog","description":"","publisher":{"@id":"https:\/\/webkul.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/webkul.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/webkul.com\/blog\/#organization","name":"WebKul Software Private Limited","url":"https:\/\/webkul.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/webkul.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-logo-accent-sq.png","contentUrl":"https:\/\/cdnblog.webkul.com\/blog\/wp-content\/uploads\/2021\/08\/webkul-logo-accent-sq.png","width":380,"height":380,"caption":"WebKul Software Private Limited"},"image":{"@id":"https:\/\/webkul.com\/blog\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/webkul\/","https:\/\/x.com\/webkul","https:\/\/www.instagram.com\/webkul\/","https:\/\/www.linkedin.com\/company\/webkul","https:\/\/www.youtube.com\/user\/webkul\/"]},{"@type":"Person","@id":"https:\/\/webkul.com\/blog\/#\/schema\/person\/c9c6288b3950490ffdb37cb2a526996e","name":"Bulbul","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/webkul.com\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/37ea7175f5ae6557d01bb38e147f6a02a540714ecdb71770d8ec554d4d34c23f?s=96&d=https%3A%2F%2Fcdnblog.webkul.com%2Fblog%2Fwp-content%2Fuploads%2F2019%2F10%2Feva.png&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/37ea7175f5ae6557d01bb38e147f6a02a540714ecdb71770d8ec554d4d34c23f?s=96&d=https%3A%2F%2Fcdnblog.webkul.com%2Fblog%2Fwp-content%2Fuploads%2F2019%2F10%2Feva.png&r=g","caption":"Bulbul"},"url":"https:\/\/webkul.com\/blog\/author\/bulbul896\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/posts\/43526","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/users\/68"}],"replies":[{"embeddable":true,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/comments?post=43526"}],"version-history":[{"count":12,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/posts\/43526\/revisions"}],"predecessor-version":[{"id":517994,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/posts\/43526\/revisions\/517994"}],"wp:attachment":[{"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/media?parent=43526"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/categories?post=43526"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/webkul.com\/blog\/wp-json\/wp\/v2\/tags?post=43526"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}