How do I set a custom order validator for shipping rates?

Shipping rates can define an order validator to determine whether they are available for a particular order.

For example, you may only want to offer a shipping rate only for certain customer groups.

First, define an availability setting to allow this:

\Aero\Cart\Models\ShippingRate::settings('availability', function (\Aero\Common\Settings\ModelSettingGroup $group) {
    $group->boolean('restricted_by_customer_group')->default(false);

    $group->eloquent('allowed_customer_groups', \Aero\Account\Models\CustomerGroup::class)->multiple()->dontLoadModels()
        ->showIf('settings.availability.restricted_by_customer_group', true);
    
    $group->eloquent('disallowed_customer_groups', \Aero\Account\Models\CustomerGroup::class)->multiple()->dontLoadModels()
         ->showIf('settings.availability.restricted_by_customer_group', true);
});

The setOrderValidator method can then use these settings to determine whether the shipping rate is available for a customer:

\Aero\Cart\Models\ShippingRate::setOrderValidator(function (\Aero\Cart\Models\ShippingRate $rate) {
    if (! $rate->settings('availability.restricted_by_customer_group')) {
        return true;
    }
  
    $disallowedGroups = $rate->settings('availability.disallowed_customer_groups') ?? [];
    $allowedGroups = $rate->settings('availability.allowed_customer_groups') ?? [];

    $customerGroupId = optional($rate->shippingMethod->order->customer)->customer_group_id ?? null;
  
    if (in_array($customerGroupId, $disallowedGroups)) {
        return false;
    }

    if (empty($allowedGroups)) {
        return true;
    }
  
    return in_array($customerGroupId, $allowedGroups);
});

The validator receives the shipping rate, order and order item group and should return true when it can be used for the order, or false when it should be excluded.


Parameters

Parameter Type Description
$rate \Aero\Cart\Models\ShippingRate The shipping rate being validated.
$order \Aero\Cart\Models\Order The order being validated.
$items \Aero\Common\Eloquent\JavaScriptableCollection The items of the order, or the order item group.


Revision #5
Created 2026-09-16 12:12:16 UTC by Ethan Payne
Updated 2026-10-02 12:59:16 UTC by Ethan Payne