How can I add a custom code handler?
You can use the addCodeHandler() method to add custom behaviour for specific codes when applied to the cart.
For example you can create a discount code that adds a free sample pack to the cart.
First, define some settings to control this behaviour:
\Aero\Common\Facades\Settings::group('free-sample', function (\Aero\Common\Settings\SettingGroup $group) {
$group->eloquent('discount', Discount::class);
$group->eloquent('variant', Variant::class)->searchField('sku', 'sku');
});
Then add a code handler to the cart that consumes these settings:
\Aero\Cart\Cart::addCodeHandler(function (Cart $cart, string $code) {
$discount = setting('free-sample.discount');
if (! $discount) {
return false;
}
if ($code !== $discount->code) {
return false;
}
$alreadyApplied = $cart->items()->contains(function (\Aero\Cart\CartItem $item) {
return $item->meta->get('is_free_sample');
});
if ($alreadyApplied) {
throw new CartModificationException(__('Discount code already applied.'));
}
$cartItem = new CartItem(
setting('free-sample.variant'),
);
$cartItem->setName('Free Sample Pack')
->setImmutable()
->setNotCombinable()
->setFree()
->setMeta('is_free_sample', true);
$cart->add($cartItem);
return true;
});
The aerocargo/automated-add-to-cart module can be used to automatically add items to the cart based on rules.