AdRock
2 years ago

Custom Validation Method [validateUniqueWith] does not exist.

Posted 2 years ago by AdRock

I am having problems with custom validation. Whenever i try to validate using a custom validation rule I get this error

BadMethodCallException in Validator.php line 3396: Method [validateUniqueWith] does not exist.

I've been following a similar question on https://laracasts.com/index.php/discuss/channels/laravel/form-validation-combination-of-fields-must-be-unique where I found the example code. I've tailored it as I use Laravel 5.3 as there is no Services folder I have created a service provider

ValidationServiceProvider.php
<?php 

namespace App\Providers\Validation;

use Validator;
use Illuminate\Support\ServiceProvider;
use App\Providers\Validation\UniqueWithValidator;

class ValidationServiceProvider extends ServiceProvider {


    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        #
    }

    /**
     * Boot the service provider.
     */
    public function boot()
    {
        $this->uniqueWithValidator();
    }

    private function uniqueWithValidator()
    {
        // Need to override the default validator with our own validator
        // We can do that by using the resolver function
        Validator::resolver(function ($translator, $data, $rules, $messages)
        {
            // This class will hold all our custom validations
            return new UniqueWithValidator($translator, $data, $rules, $messages);
        });
    }
}

I have created a directory called Validation in the Providers directory and I've placed this file inside it

<?php 

namespace App\Providers\Validation;

use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Validator;

class UniqueWithValidator extends Validator {

    public function validateUniqueWith($attribute, $value, $parameters)
    {
        $result = DB::table($parameters[0])->where(function($query) use ($attribute, $value, $parameters) {
            $query->where($attribute, '=', $value) // where firstname = value
                ->orWhere($parameters[1], '=', $value); // where lastname = value
        })->first();

        return $result ? false : true;
    }
}

I've added this to config/app.php providers

App\Providers\ValidationServiceProvider::class,

I'm convinced it's to do with namespacing but not sure.

Please sign in or create an account to participate in this conversation.