Laravel validation after hook in form request file

Submitted by asifzcpe - 3 years ago

if you want to run custom validation having a long function in laravel request file, you can use the following tricks to get the things done using withValidator method.

class StoreBlogPost extends FormRequest
{
    public function authorize()
    {
        return true;
    }

    public function rules()
    {
        return [
            'title' => 'required|unique:posts|max:255',
            'body' => 'required',
        ];
    }

    //this method will be called automatically after basic validation and this is laravel's built in function
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }
}