How do I set a custom order validator for shipping methods?
Shipping methods can define an order validator to determine whether they are available for a particular order.
For example, you may only want to offer some shipping methods on certain days.
First we will define an availability setting for each day:
$days = collect([
'sunday' => false,
'monday' => true,
'tuesday' => true,
'wednesday' => true,
'thursday' => true,
'friday' => true,
'saturday' => false,
]);
\Aero\Cart\Models\ShippingMethod::settings('availability', function (\Aero\Common\Settings\ModelSettingGroup $group) use ($days) {
$days->each(function (bool $available, string $day) use ($group) {
$group->boolean("{$day}_delivery")->default($available);
});
});
The setOrderValidator method can then use these settings to determine whether the shipping method is available today:
\Aero\Cart\Models\ShippingMethod::setOrderValidator(function (\Aero\Cart\Models\ShippingMethod $method) use ($days) {
$day = $days->keys()[now()->dayOfWeek];
return $method->setting("availability.{$day}_delivery");
});
The validator receives the shipping method, 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 |
$method |
\Aero\Cart\Models\ShippingMethod |
The shipping method being validated. |
$order |
\Aero\Cart\Models\Order |
The order being validated. |
$orderItemGroup |
string|null |
The order item group being validated (null when not in a group). |