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.
$data = [ 'coupon' => 'PIZZA_PARTY', 'items' => [ [ 'id' => 1, 'quantity' => 2 ], [ 'id' => 2, 'quantity' => 2, ], ],]; $validator = Validator::make($data, [ 'coupon' => 'exists:coupons,name', 'items' => 'required|array', 'items.*.id' => 'required|int', 'items.*.quantity' => 'required|int',]); $validator->sometimes('coupon', 'prohibited', function (Fluent $data) { return collect($data->items)->sum('quantity') < 5;}); // throws a ValidationException as the quantity provided is not enough$validator->validate();
Tip given by @cerbero90
Enjoyed This Tip?
Get access to all premium tutorials, video and text courses, and exclusive Laravel resources. Join our community of 10,000+ developers.
Recent Courses
Laravel Coding with AI Agents: Cursor, Claude Code, Codex
5 lessons
1 h 01 min
Laravel Modules and DDD
16 lessons
1 h 59 min
Filament 4 From Scratch
28 lessons
2 h 25 min