I created a custom module for applying custom coupon code programmatically in magento 2. For shopping cart rule.

I have only coupon code with block and model collection check below image.

enter image description here

How can do it ? Any suggestion for that ?

  • hello.. I want to do same functionality.. coupon code is exist in custom table and I want to apply it from custom table.. is it possible? I mean u did that kind of functionality? Commented Jul 14, 2021 at 11:24

1 Answer 1


First you need to inject a few classes in your constructor:

protected $cart;
protected $quoteRepository;

public function __construct(
    \Magento\Checkout\Model\Cart $cart,
    \Magento\Quote\Api\CartRepositoryInterface $quoteRepository
) {
    $this->cart= $cart;
    $this->quoteRepository = $quoteRepository;

Then in your code you can do: Data.php in helper

public function getCouponCode(){
    $cartQuote = $this->cart->getQuote();
    return $cartQuote->getCouponCode();

Here use own create function replace $cartQuote->getCouponCode(); to $cartQuote->getOwnFuction(); And put code in getOwnFuction() for apply custom couponCode

And then i put in my function: Vendor\Shipping\Model\Quote\Address\Rate.php

public function importShippingRate(\Magento\Quote\Model\Quote\Address\RateResult\AbstractResult $rate)
   $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
   $helper = $objectManager->create('Vendor\Shipping\Helper\Data');

   $couponCode = $helper->getCouponCode();
   echo 'CouponsCode = '.$couponCode;
  • Thanks for your answer but, i don't know, in which file put above code? Because this is new for me Commented Oct 10, 2016 at 8:55
  • @PayalPatel well this depends on how you developed your module. Put that code in the class that you're using to apply the coupon code programmatically Commented Oct 10, 2016 at 9:00
  • Can restrict method for particular coupon code using above code @Raphael Commented Oct 10, 2016 at 9:15
  • 1
    @PayalPatel yes you just need to replace $couponCode with your particular coupon code Commented Oct 10, 2016 at 9:18
  • 1
    can anyone tell how can i apply a coupon code in a controller if i already have the coupon code ? Commented Jan 23, 2017 at 11:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.