R
R
Rodion Yurchenko2019-05-22 22:57:28
Laravel
Rodion Yurchenko, 2019-05-22 22:57:28

How can I add a Rule to the validator so that the rule fires after the main validation?

Good afternoon. Given:
The form for creating a booking for visiting a massage
The form has 3 fields - time_from, time_to, massage_cabinet
The controller has the following code:

public function validation()
{
    $request_data = request()->only(['meet_room_id', 'time_from', 'time_to', 'date']);

    $validation1 = Validator::make($request_data, [
        'time_from'=>['required','date_format:H:i'],
        'time_to'=>'required|date_format:H:i|after:time_from',
        'meet_room_id'=>["required","exists:meet_rooms,id", new BookingCalendarRule($request_data)]
    ]);
}

Question: how to do so that the "simple validation" of the type required, date_format, etc. passes first, and then the BookingCalendarRule starts?
The main catch is that the BookingCalendarRule uses the time_from parameter of the same request, and if the time format is not correct initially, then an invalid parameter will be passed to the Rule.
I understand that I myself pass $requested_data there, which is not checked, but I cannot pass validated() data there, since at that time they do not exist.
The closest way out of the situation that I found is to make 2 check blocks - first for "simple rules", and then more complex ones.
Is it correct? Can it be done in a more elegant way?
I know that it is possible to make custom requests and move the validation there - in fact, it is so, just so as not to write a bunch of "example" code here. The question is about the blocks themselves with validation.
Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex Wells, 2019-05-23
@aassdds

There is a rule called bail. Add it to each field and the validator will fall as soon as at least one check is not passed, which means that the queue will not reach your custom rule.
Plus, you don’t need to pass any requests to the custom rule - everything that is needed is passed to the passes() method of the rule:
You pass only the name of some additional field to the rule constructor - of the time_from type.

X
XNicON, 2019-05-23
@XNicON

The validator validates fields, not whole constructs.
Everything is perfectly described in the documentation, for your case there is an after hook
https://laravel.com/docs/5.8/validation#after-vali...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question