shopping cart observer

shopping cart observer

August 1, 2026 · Illustrated author avatarBy Stefan Bogdanescu
shopping cart observer

Handling Surcharges for Free Items in Magento

As an e-commerce developer specializing in Magento, I often encounter scenarios where merchants need to add surcharges or discounts based on complex conditions. One such situation involves applying a shipping fee when a customer adds a certain number of free samples to their cart.

Let’s break down your requirement and discuss the best approach using observers in Magento 2.

Understanding Your Requirements

You’re selling fabric/material with an expensive price point and allowing customers to purchase free “samples”. Here are the key conditions:

  1. Samples are free ($0.00).
  2. If a customer has 5 or more samples (no more than 15), charge a $20 surcharge for shipping.

Why Use Observers?

Observers in Magento allow you to hook into specific events and modify data accordingly. In this case, we can use the sales_quote_collect_totals event to check if the conditions are met and add the surcharge when needed.

Step 1: Identify the Free Sample Products

Ensure that your sample products have a price of $0.00 or use a special price rule to set them as free items. This will make it easier for us to identify samples in the observer.

Step 2: Create an Observer Method

First, navigate to app/code/Magento/Quote/etc/events.xml and add your event listener:

<event name="sales_quote_collect_totals">
    <observer name="your_vendor_module_name" instance="YourVendor\ModuleName\Model\Observer" />
</event>

Next, create the observer file at app/code/YourVendor/ModuleName/Model/Observer.php:

namespace YourVendor\ModuleName\Model;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Quote\Model\Quote;

class Observer implements ObserverInterface
{
    private $quoteItemCollectionFactory;

    public function __construct(
        \Magento\Quote\Model\ResourceModel\Quote\Item\CollectionFactory $quoteItemCollectionFactory
    ) {
        $this->quoteItemCollectionFactory = $quoteItemCollectionFactory;
    }

    public function execute(Observer $observer)
    {
        /** @var Quote $quote */
        $quote = $observer->getEvent()->getQuote();

        // Fetch free samples in the cart
        $freeSamples = $this->getFreeSampleItems($quote);

        if (count($freeSamples) >= 5 && count($freeSamples) <= 15) {
            $quote->setShippingAmount(20.00);
        }
    }

    private function getFreeSampleItems(Quote $quote)
    {
        // Fetch free sample items using the quote item collection
        $collection = $this->quoteItemCollectionFactory->create();
        $collection->addFieldToFilter('price', ['eq' => 0]);
        $collection->setQuoteId($quote->getId());

        return $collection;
    }
}

Remember to replace YourVendor and ModuleName with your actual vendor code and module name.

Step 3: Add the Surcharge

In the execute method, we check if there are 5 or more free samples in the cart. If the condition is met, we set the shipping amount to $20 using $quote->setShippingAmount(20.00).

Conclusion

Using observers in Magento allows you to handle complex pricing rules efficiently and maintain a clean separation of concerns between your business logic and core Magento functionality.

This approach provides an elegant solution for adding surcharges based on the number of free items in the cart, ensuring that customers who order multiple samples are charged accordingly.

For more advanced customizations and best practices in Magento development, I recommend exploring our comprehensive guides at https://laravelcompany.com/magento-development-guides.

By following this observer pattern, you can create a robust and maintainable solution for handling surcharges and discounts based on complex cart conditions in your Magento 2 store.

Magento 2 Checkout Catalog Extensions

Our network