Tomáš Hrušo Tomáš Hrušo - 11 days ago 6
PHP Question

Laravel validate request as a whole

I would like to validate given lecture. There are some validation rules but I want to extend it somehow with validation function which takes 3 attributes as arguments and check others lectures in database and return valid if none of lectures overlap. Lectures have start, end DateTime attributes.

Validation function is

private function noOtherLecturesOnGivenTime($start, $end, $hall)
{
if(!$start instanceof Carbon) {
$start = new Carbon($start);
}

if(!$end instanceof Carbon) {
$end = new Carbon($end);
}

if(is_null($hall)) {
return true; // if there is no hall defined, all times are acceptable
}

if(!$hall instanceof Model) {
/** @var Hall $hall */
$hall = Hall::find($hall);
}
$overlappingLectures = $hall->lectures()->get()->filter(function ($lecture) use ($start, $end) {
// (Ts < e) and (Te > s)
return $start->lt($lecture->end) and $end->gt($lecture->start);
});

return $overlappingLectures->count() === 0;
}


I don't know how and where to put this function so Laravel's validator throws exception and I could specify error message with i18n.

Thanks

Answer

Check out the documentation about custom validation rules.

From creating the rule to specifiying error messages, there is a full exemple there :

Laravel custom validation rules documentation

For your case, you can fetch the parameters from the request in the validation method.

I think the validation rule will still occur even if other parameters aren't set, don't forget to check if they are in the request

Comments