Skip to main content
Shipping · Revision #4

How do I set a custom price totalizer for shipping rates?

How do I set a custom price totalizer for shipping rates?

Shipping rates can define a custom price totalizer to adjust the calculated shipping price before it is returned to the customer.

For example, you may want to add a fixed cost for each item in the order.

First, define the cost per item on the shipping method:

\Aero\Cart\Models\ShippingMethod::settings('extras', function (\Aero\Common\Settings\ModelSettingGroup $group) {
    $group->float('cost_per_item');
});

The setPriceTotalizer method can then add the per-item cost to the shipping rate's calculated price:

\Aero\Cart\Models\ShippingRate::setPriceTotalizer(function ($price, \Aero\Cart\Models\ShippingRate $rate) {
    $costPerItem = $rate->setting('extras.cost_per_item')
        ?? $rate->shippingMethod->setting('extras.cost_per_item');

    if (! $costPerItem) {
        return null;
    }

    $itemAmount = $rate->order->items->sum('quantity');

    return $price + ($itemAmount * $costPerItem * 100);
});

The totalizer receives the price and the shipping rate as parameters and should return the total in pence or null.

Returning null means that the default price totalizer will be used.


Parameters

Parameter Type Description
$price
float
The total price in pence.
$rate
\Aero\Cart\Models\ShippingRate
The shipping rate being evaluated.