Validator::sometimes() method allows us to define when a validation rule should be applied

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

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 68 courses (1183 lessons, total 43 h 18 min)
  • 90 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent New Courses