Search code examples
phplaravellumen

Presence verifier has not been set exception on validator rule exists Lumen 8


I am trying to validate some input with laravel validator class and I am having Presence verifier has not been set. error. I am trying to use Validator class by injecting the Illuminate\Validation\Factory class to my controller and using

$validator = $this->validator->make($request->all(), [
            'email' => 'required|unique:users|email:rfc,dns|max:65',
            'password' => 'required|string|min:6',
        ]);

as in the example and in this issue they suggesting to enabling $app->withEloquent(); and I have it enabled already but still having problem. but if I use it directly from $this->validator() function it doesn't give any error but I need custom error response thats why i need to use it other way


Solution

  • I recently ran into the obscure error you're talking about, and here are a few things that I (and a more experienced coworker) learned:

    1. This will only really happen if you try to do your own custom validation, the built-in validation for Laravel (Lumen is a subset of Laravel) takes care of all of this behind the scenes.
    2. Even if you use your own custom validation, this will only affect validation rules that check the database (like exists or unique).
    3. You should be using the Contract Validation Factory (Illuminate\Contracts\Validation\Factory) instead of Contract Factory (Illuminate\Validation\Factory). See this post for more info: https://github.com/laravel/lumen-framework/issues/584
    4. Even when you use the Contract Validation Factory, you need to manually specify your own Presence Verifier. For some reason the framework doesn't take care of it for you (possibly a bug that will be fixed in later versions?).

    So... a little more info for you:

    What is a Presence Verifier?

    It checks if the thing you're validating is in the database. If you open the framework's ValidationServiceProvider.php file in your project, it gives a good explanation of what it is:

    The validation presence verifier is responsible for determining the existence of values in a given data collection which is typically a relational database or other persistent data stores. It is used to check for "uniqueness" as well.

    How do I manually set a Presence Verifier?

    Go to the boot() function on your custom validator and insert something like this:

    if (isset($app['db'], $app['validation.presence'])) {
        $validator->setPresenceVerifier($app['validation.presence']);
    }
    return $validator;
    

    The code above is a slightly modified version of what Laravel does under the hood to set the Presence Verifier. That's how we fixed the issue.

    Here's the only other StackOverflow article I could find on the issue: laravel validation unique rule