How To

Apply Coupon Code While Programmatically Adding Product to Cart In Magento 2

Hello Magento Folks?,

How’s everything going on? Welcome back to another How to Magento 2 Series, I consider all of you are safe and productive at home. To make this even more fertile, Today I have come up with the topic that how can we Apply Coupon Code While Pragmatically adding product to cart in Magento 2. Before that, If you have missed our latest blog on How to Add Custom Block After Shipping and Billing Address in Admin Sales order view page in Magento 2 Then check it. So let’s begin?.

Introduction:

Nowadays, everyone is finding a reasonable price for any of the products they want. So discounts on products play a big role here. The more discount and offers you will give, the more sales you are going to get. So here is how we can offer and apply discount in your E-commerce website. Usually, we offer some discount to the customer while they add the product to the cart, but what if that thing requires to apply while adding product to cart programmatically. So, here is the way how you can achieve that.

 Let’s say for a For E.g.: I have one product with id ‘1’ and want to apply the “HAPPY CODING” coupon code while applying that product to cart programmatically.

namespace Vendor\Extension\Controller\Index;
 
class Addtocart extends \Magento\Framework\App\Action\Action
{
 protected $productrepository;
 protected $cart;
 protected $formKey;
 
 public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productrepository,
     \Magento\Checkout\Model\Cart $cart,
        \Magento\Framework\Data\Form\FormKey $formKey
 )
 {
     $this->cart = $cart;
     $this->productrepository = $productrepository;
     $this->formKey = $formKey;
     parent::__construct($context);
 }
 
 public function execute()
 {
     try {
         $productId = 1;
         $qty = 4;
         $coupancode = "HAPPYCODING";
         $product = $this->productrepository->getById($productId);
         $formKey = $this->formKey->getFormKey();
         $paramater = array(
             'product' => $productId,
             'qty' => $qty,
             'form_key' => $formKey,
         );
         $this->cart->addProduct($product, $paramater);
         $this->cart->getQuote()->setCouponCode($coupancode);
         $this->cart->save();
         return true;
     } catch (\Exception $e) {
         return __($e->getMessage());
     }
 }
}

Final Words

Assuming that you are now equipped with Applying Coupon Code While Pragmatically adding product to cart in Magento 2. With the help of these codes, you can successfully add discounts directly while adding products to cart programmatically. So, Using the Above code we can apply Coupon Code easily. You are free to play around and customize these codes as per your requirements for fetching data. If you face any problems while implementing, then contact our support team. We will be more than happy to help you.

Stay connected, stay safe!

Happy coding!!

Click to rate this post!
[Total: 4 Average: 5]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

View Comments

Recent Posts

How to Add Tooltip in Checkout Shipping Field in Magento 2?

Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…

2 days ago

How to Integrate and Use MongoDB with Laravel?

MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…

3 days ago

NodeJS | Callback Function

In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…

4 days ago

How to Show SKU in Order Summary in Magento 2?

Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…

6 days ago

Best Colors to Use for CTA Buttons

The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…

1 week ago

Magento 2: How to Save Custom Field Value to quote_address for Multi-Shipping Orders

Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…

1 week ago