7

I need to get the details of an already created discount rule in magento 2.

I am using this code but don't work

public function __construct(
    \Magento\SalesRule\Model\Coupon $coupon
)
{
    $this->coupon = $coupon;
    parent::__construct($context);
}

...

public function getDiscount($couponCode)
{
    $ruleId =   $this->coupon->loadByCode($couponCode)->getRuleId();
    return $ruleId;

}

2 Answers 2

8

I wasn't that far from the solution:

protected $coupon;
protected $saleRule;     

public function __construct(
    \Magento\SalesRule\Model\Coupon $coupon,
    \Magento\SalesRule\Model\Rule $saleRule
)
{
    $this->coupon = $coupon;
    $this->saleRule = $saleRule;
    parent::__construct($context);
}

...

public function getDiscount($couponCode)
{
    $ruleId =   $this->coupon->loadByCode($couponCode)->getRuleId();
    $rule = $this->saleRule->load($ruleId);
    return $rule->getDiscountAmount();
}

Of course need a bit of validation to be sure the rule exist

5
protected $couponModel;

protected $ruleRepository;     

public function __construct(
    \Magento\SalesRule\Model\Coupon $couponModel,
    \Magento\SalesRule\Api\RuleRepositoryInterface $ruleRepository
) {
    $this->couponModel = $coupon;
    $this->ruleRepository = $saleRule;
}


public function getDiscount($couponCode)
{
    $ruleId =  $this->couponModel->loadByCode($couponCode)->getRuleId();
    $rule = $this->ruleRepository->getById($ruleId);
    return $rule->getDiscountAmount();
}
8
  • @Price Patel, is it possible to get all coupons collections.Actually i am creating coupons programmatically with skus conditions.now problem is that i am not able to get coupons data(here i want to get skus with coupons). Jul 24, 2019 at 13:45
  • @HiteshBalpande Use Magento\SalesRule\Model\ResourceModel\Rule\Collection class with ->addFieldToFilter('coupon_type', 2) to get all coupon collection Jul 24, 2019 at 16:31
  • I'd like to give a try on getList instead
    – PY Yick
    Dec 30, 2021 at 6:42
  • @Price Patel, you said As per Magento 2 coding standards, we should user API interface instead of direct use of the model so why don't you use \Magento\SalesRule\Api\Data\CouponInterface instead of coupon model? Jul 12, 2022 at 10:09
  • 1
    we dont have any method to get rule data using coupon in CouponInterface @MarceloRodovalho Nov 30 at 10:00

Your Answer

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

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