Search code examples
phplaravelvalidationuniqueregistration

how to validate unique combination of two fields in Laravel?


I am trying to add validation constraints on the registration of a new user and I want the combination of two fields be unique in the database. The error that i get is from the database saying i have a integrity constraint violation. the table I have is called users and the fields i want to have unique combination are called ssn and lastfour.

I added the line $table->unique(array('ssn','lastfour')); in the user migration and I also added some fields in the registration which work fine and the database is ok. I tried the solution in a similar question posted about 9 months ago Laravel unique validation on multiple columns but i get undefined variable on line "Rule::unique('servers')->where(function ($query) use($ssn,$lastfour)"

protected function validator(array $data)
{
    return Validator::make($data, [
        'name' => ['required', 'string', 'max:255'],
        'lastname' => ['required', 'string', 'max:255'],
        'username' => ['required', 'string', 'max:255', 'unique:users'],
        'ssn' => ['required', 'string', 'regex:/^[0-9]*$/','max:8', 'min:8'],
        'lastfour' => ['required', 'string', 'regex:/^[0-9]*$/','max:4', 'min:4'],
        'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
        'password' => ['required', 'string', 'min:6', 'confirmed'],
    ]);
}

i tried the following code

'lastfour' => ['required', 'string', 'regex:/^[0-9]*$/','max:4', 'min:4', 
                        Rule::unique('users')->where(function ($query) use 
                        ($ssn, $lastfour){
                            return $query->where('ssn', $ssn)
                            ->where('lastfour', $lastfour);
                        })
        ],

Solution

  • $ssn and $lastfour don't seem to be defined anywhere. You can try the following instead:

    protected function validator(array $data)
    {
        $uniqueRule =  Rule::unique('users')->where(function ($query) use 
                        ($data){
                            return $query->where('ssn', $data['ssn']??'')
                            ->where('lastfour', $data['lastfour']??'');
                        });
    
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255'],
            'lastname' => ['required', 'string', 'max:255'],
            'username' => ['required', 'string', 'max:255', 'unique:users'],
            'ssn' => ['required', 'string', 'regex:/^[0-9]*$/','max:8', 'min:8',  $uniqueRule ],
            'lastfour' => ['required', 'string', 'regex:/^[0-9]*$/','max:4', 'min:4'],
            'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
            'password' => ['required', 'string', 'min:6', 'confirmed'],
        ]);
    }