Magento 2 – Apply Existing Coupon Code Programmatically

checkoutcontrollerscoupondiscountmagento2

I try to apply an existing coupon code programmatically in a controller by coupon id.

The only thing I found these code lines for Magento 1.

Mage::getSingleton('checkout/cart')
        ->getQuote()
        ->setCouponCode($coupon)
        ->collectTotals()
        ->save();

Does anyone know how can I do this in magento 2?

Best Answer

Use Checkout model session to get quote data.

 /** @var \Magento\Checkout\Model\Session $checkoutSession**/

$this->checkoutSession->getQuote()->setCouponCode($couponCode)
                                  ->collectTotals()
                                  ->save();

Remember to inject \Magento\Checkout\Model\Session in your constructor.

Take a look: vendor/magento/module-checkout/Controller/Cart/CouponPost.php