Skip to main content
Shipping · Revision #3

How do I set a custom applicable items filter for shipping rates?

How do I set a custom applicable items filter for shipping rates?

Shipping rates can define a custom-applicable items filter to control which order items are considered when determining whether a rate is applicable.

For example, you may want to restrict a shipping method to products from specific manufacturers.

First, define settings for enabling manufacturer restrictions and selecting the allowed and disallowed manufacturers:

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

    $group->eloquent('allowed_manufacturers', \Aero\Catalog\Models\Manufacturer::class)->multiple()->dontLoadModels()
        ->showIf('settings.availability.restricted_by_manufacturer', true);

    $group->eloquent('disallowed_manufacturers', \Aero\Catalog\Models\Manufacturer::class)->multiple()->dontLoadModels()
        ->showIf('settings.availability.restricted_by_manufacturer', true);
});

The setApplicableItemsFilter method can then filter out items that don't meet the manufacturer restrictions:

\Aero\Cart\Models\ShippingRate::setApplicableItemsFilter(function ($items, \Aero\Cart\Models\ShippingRate $rate) {
    if (! $rate->shippingMethod->setting('availability.restricted_by_manufacturer')) {
        return $items;
    }

    $allowedManufacturerIds = $rate->shippingMethod->setting('availability.allowed_manufacturers');
    $disallowedManufacturerIds = $rate->shippingMethod->setting('availability.disallowed_manufacturers');

    $hasDisallowedItem = $items->some(function (\Aero\Cart\Models\OrderItem $item) use ($allowedManufacturerIds, $disallowedManufacturerIds) {
        if (in_array($item->buyable->manufacturer_id, $disallowedManufacturerIds)) {
            return true;
        }
        
        if (empty($allowedManufacturerIds)) {
            return false;
        }
    
        return ! in_array($item->buyable->manufacturer_id, $allowedManufacturerIds);
    }
    
    if ($hasDisallowedItem) {
        return collect();
    }

    return $items;
});

The filter receives the order price and the shipping rate as parameters and should return a collection of applicable items.


Parameters

Parameter Type Description
$items
\Aero\Common\Eloquent\JavaScriptableCollection
The order items being evaluated.
$rate
\Aero\Cart\Models\ShippingRate
The shipping rate being evaluated.