Reading list Switch to dark mode

    How to Add Product in Cart in Magento 2

    Updated 23 February 2024

    To add a product to the cart programmatically with a custom price in Magento 2.

    <?php
    
    namespace Webkul\Test\Controller\Index;
    
    use Magento\Framework\App\Action\Action;
    use Magento\Framework\App\Action\Context;
    use Magento\Catalog\Model\ProductFactory;
    use Magento\Checkout\Model\Cart;
    use Magento\Catalog\Model\Product;
    
    class AddProducttocart extends Action
    {
        /**
         * @var PageFactory
         */
        protected $_resultPageFactory;
    
        protected $cart;
        
        protected $product;
    
        
        public function __construct(
            Context $context,
            PageFactory $resultPageFactory,
            \Magento\Framework\Data\Form\FormKey $formKey,
            Cart $cart,
            Product $product
        ) {
            $this->_resultPageFactory = $resultPageFactory;
            $this->formKey = $formKey;
            $this->cart = $cart;
            $this->product = $product;
            parent::__construct($context);
        }
    
       
        public function execute()
        {
           
            $productId = 2;
            $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' =>$productId,//product Id
                'qty'   =>1,//quantity of product
                'price' =>50 //product price
            );
            $product = $this->product->load($productId);
            $this->cart->addProduct($product, $params);
            $this->cart->save();
    
    
            $resultPage = $this->_resultPageFactory->create();
            return $resultPage;
        }
    }

    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.

    Searching for an experienced
    Magento 2 Company ?
    Find out More
    . . .

    Leave a Comment

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


    12 comments

  • 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