You can get Sales rule (Cart Price rules) data by id in Magento 2 to fetch all the Cart rules related information.
You required Sales Rule id to retrieve the data of sales rule.
Just refer the below code snippet,
<?php
namespace Jesadiya\SalesRule\Model;
use Exception;
use Psr\Log\LoggerInterface;
use Magento\SalesRule\Api\Data\RuleInterface;
use Magento\SalesRule\Api\RuleRepositoryInterface;
class SalesRuleById
{
/**
* @var LoggerInterface
*/
private $logger;
/**
* @var RuleRepositoryInterface
*/
protected $ruleRepository;
public function __construct(
LoggerInterface $logger,
RuleRepositoryInterface $ruleRepository
) {
$this->logger = $logger;
$this->ruleRepository = $ruleRepository;
}
/**
* @return RuleInterface|null
*/
public function getRuledata($ruleId): ?RuleInterface
{
$salesRule = null;
try {
$salesRule = $this->ruleRepository->getById($ruleId);
} catch (Exception $exception) {
$this->logger->error($exception->getMessage());
}
return $salesRule;
}
}
You can get the data of sales rule by id,
$ruleId = 1;
$salesRuledata = $this->getRuledata($ruleId);
echo $salesRuledata->getName();
