We've recently built Upserver.online, a sophisticated health checker for Laravel applications with support for databases, queues, broadcasting, mail, caching, security checks and it even monitors your uptime, DNS records, SSL certificates and mixed content. Create an account and follow us on Twitter!

Working with the Validator instance in Form Requests

January 20, 2017

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:


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.