The laravel Validator::sometimes()
method allows us to define when a validation rule should be applied, based on the input provided.
The snippet shows how to prohibit the use of a coupon if the quantity of the purchased items is not enough.
1$data = [ 2 'coupon' => 'PIZZA_PARTY', 3 'items' => [ 4 [ 5 'id' => 1, 6 'quantity' => 2 7 ], 8 [ 9 'id' => 2,10 'quantity' => 2,11 ],12 ],13];14 15$validator = Validator::make($data, [16 'coupon' => 'exists:coupons,name',17 'items' => 'required|array',18 'items.*.id' => 'required|int',19 'items.*.quantity' => 'required|int',20]);21 22$validator->sometimes('coupon', 'prohibited', function (Fluent $data) {23 return collect($data->items)->sum('quantity') < 5;24});25 26// throws a ValidationException as the quantity provided is not enough27$validator->validate();
Tip given by @cerbero90