Working with the Validator instance in Form Requests

One undocumented gem I found today in the Laravel Framework is the withValidator method on a FormRequest class. If this method exists on your request class, this method gets called with the Validator instance as first argument. It allows you to interact with the validator instance before the actual validation happens.

Now, why do you want this? You can define your rules in the rules method right? One of the things you could do is adding 'After Validation Hooks' to the validator. According to the documentation this allows you to attach callbacks to be run after validation is completed. You can read more about this and other cool features of the validator in the documentation.

Here is an example of a request class that has a withValidator method that adds a hook the validator:

<?php
 
namespace App;
 
use Illuminate\Foundation\Http\FormRequest;
 
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!');
}
});
}
}

Pretty cool if you ask me! If you're curious where this magic happens, take a look at the getValidatorInstance method on the FormRequest class. You can find it in the Illuminate\Foundation\Http namespace.