I try to create a code to generate a lot of coupon code randomly, but the problem is i need to check if the coupon code already exist or not, is there a way to do this?

protected $_coupon;  

in construct add this

   public function __construct(     
        \Magento\SalesRule\Model\Coupon $coupon
    ) {
        $this->_coupon = $coupon;

Now you can use like this,

 $ruleId=   $this->_coupon->loadByCode($couponCode)->getRuleId();

 if (empty($ruleId)) {
            // generate coupon code

Where $couponCode is your coupon code

  • so if the $ruleId is empty, my coupon code is valid?
    – Hunter
    Jun 6 '17 at 7:56
  • Yes ...... , @Hunter
    – Keyur Shah
    Jun 6 '17 at 7:57
  • this worked for me
    – Jiyaad.D
    Mar 22 '19 at 21:57
  • how to get all list of coupon codes which can apply on cart page in magento 2
    – 55840
    Apr 5 '19 at 9:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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