max_period:start_date,duration,metric
The difference betweent the field under validation, and the start_date field must not be greater than the specified duration in the given metric.
Metrics:
- hours,
- days*,
- weeks,
- months,
- years
* default
Example
$this->validator($request, [
'date_from' => 'date_format:Y-m-d',
'date_to' => 'date_format:Y-m-d|after:date_from|max_period:date_from,2,days',
]);
Implementation
Validator::extend('max_period', function ($attribute, $value, $parameters, $validator) {
$data = $validator->getData();
$start = Carbon::parse($data[$parameters[0]]);
$end = Carbon::parse($value);
$duration = $parameters[1];
$metric = array_get($parameters, 2, 'days');
$method = studly_case('diffIn'.$metric);
$diff = $start->$method($end);
return $diff <= $duration;
}, 'Max allowed period is :duration :metric.');
Validator::replacer('max_period', function ($message, $attribute, $rule, $parameters) {
return str_replace(
[
':duration',
':metric',
],
[
$parameters[1],
array_get($parameters, 2, 'days'),
],
$message
);
});