Skip to main content

Load sales rule by coupon code in Magento 2

· 2 min read

In this article, we will see how to get the rule by the coupon code in Magento 2.

First, we will use the CouponFactory to create a Coupon model instance. Using factories is the second best practice to get an instance of a model in Magento if it's not possible to do so using a Repository.

Afterwards, we load the coupon by its code (in our example, our coupon code is "desc10").

Next, we will fetch the rule_id of the rule associated with the coupon and load the Rule model by its id using the RuleRepository.

In our specific example, we also fetch the discount amount of the rule associated with the coupon code (in our example, it's a 10% discount).

The code

Use the following code snippet anywhere in your code to obtain the rule by the coupon code:


<?php
namespace Mexbs\SomePlugin;

class SomeClass
{
protected $couponFactory;
protected $ruleRepository;

public function __construct(
\Magento\SalesRule\Model\CouponFactory $couponFactory,
\Magento\SalesRule\Model\RuleRepository $ruleRepository
) {
$this->couponFactory = $couponFactory;
$this->ruleRepository = $ruleRepository;
}

public function someFunction()
{
$couponCode = "disc10";
$coupon = $this->couponFactory->create()->loadByCode($couponCode);

$ruleDiscountAmount = null;
if($coupon->getRuleId()){
$rule = $this->ruleRepository->getById($coupon->getRuleId());
if($rule){
$ruleDiscountAmount = $rule->getDiscountAmount();
}
}

// do something
}
}


To sum up

In this article, we showed how to get the rule from coupon code using Magento 2 best coding practices.

info

This code was tested on Magento CE 2.4.7-p3