Magento, Magento 2

How to Get Applied Cart Rule for Quote in Magento 2

How to Get Applied Cart Rule for Quote in Magento 2

In this tutorial, Today I will explain to how to get applied cart rule for quote in Magento 2. Cart price rules is special rules with the specific condition which you define in the configuration.

The customers can able to apply coupon code/discount on the cart page based on configuration. So, if you want to get details of the applied cart rule then, you need to follow the below steps :

You may also like this :

First of all, Let’s assume that you have created a simple module. Now, I have added code inside the block. You can use the below code where you want to use it.

<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\Helloworld\Block;

class Helloworld extends \Magento\Framework\View\Element\Template
{
    /**
     * @var \Magento\Checkout\Model\SessionFactory
     */
    protected $sessionFactory;

    /**
     * @var \Magento\Quote\Model\QuoteFactory
     */
    protected $quoteFactory;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Checkout\Model\SessionFactory           $sessionFactory
     * @param \Magento\Quote\Model\QuoteFactory                $quoteFactory
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Checkout\Model\SessionFactory $sessionFactory,
        \Magento\Quote\Model\QuoteFactory $quoteFactory,
        array $data = []
    ) {
        $this->sessionFactory = $sessionFactory;
        $this->quoteFactory = $quoteFactory;
        parent::__construct($context, $data);
    }

    public function getAppliedIds()
    {
        $quoteId = $this->sessionFactory->create()->getQuote()->getId();
        $quote = $this->quoteFactory->create()->loadActive($quoteId);
        $salesruleIds = explode(',', $quote->getAppliedRuleIds());
        return $salesruleIds;
    }
}

Here, getAppliedIds() function will return rule ids if applied on the currently logged-in user quote.

That’s it !!!

I hope this blog is easy to understand how to get applied cart rule for quote in Magento 2.In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with a proper solution.

Stay Safe and Stay Connected !!

Tagged , ,