Execute code after successful validation in a form request,

Published 9 months ago by phpMick

What is the simplest way to do this?

I am trying:


    public function withValidator($validator)
    {

        $validator->after(function ($validator) {

                $validator->errors()->add('field', 'Something is wrong with this field!');




        });
    }

But it executes in success and failure.

Is there a way to execute code just after successful validation?

Thanks,

Mick

bobbybouwmann

This sounds like a code smell. What is your use case? You want to change the data after validation?

wilk_randall

You could do something like:


public function withValidator($validator)
{
    if ($validator->fails()) {
        dd($validator->errors());
    }
}

phpMick

I want to add some extra validation.

I am validating arrays, using the standard validation:

'start.*'=>'nullable|date|before:end_date',
'end.*'=>'nullable|date|after:start_date',

Now I want to validate the 'rows' in the array against each other. I won't be modifying the data but I am hoping to add to the failure messages and set failure.

Mick

martinbean

@phpMick You’re able to add validation rules in the withValidator(), but you can’t perform any additional validation in the form request after the original validation’s passed.

The reason being, it implements the ValidatesWhenResolved class. That means, if no error’s thrown during validation, it’s passes. So you’ll need to do any additional validation in your controller if you wanted to run it after the validation in the form request.

phpMick

Thanks Martin,

I have come to the conclusion that I need to just write my own validation for this. I am currently adding it all to the controller, just as you have suggested.

shez1983

you can MODIFY the form request class.. for example you can do something like:

       if (isset($this->request->get('sale')['enabled']))
        {
            $rules['sale.price']      = 'required|integer';
            $rules['sale.start_date'] = 'required|integer';
            $rules['sale.end_date']   = 'required|integer';
        }

Please sign in or create an account to participate in this conversation.