Customize Form Request Validation with withValidator in Laravel

Hello Artisan,

In this tutorial, I will show you Laravel tips. Hope it will be helpful for you. You will notice that when we create a form request and use this to validate form data, then we can not give our custom error messages.

Did you know that Laravel has a built-in function which is called when validation failed? So you can use this function to throw a custom error message to users. Let's see the example code:

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

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

    
    public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            if ($this->somethingElseIsInvalid()) {
                $validator->errors()->add('field', 'Something is wrong with this field!');
            }
        });
    }
}

 

This withValidator method will be called automatically after basic validation and this is laravel's built in function. Hope it can help you.

 

Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js