Laravel form validation unique using 2 fields

前端 未结 5 1649
渐次进展
渐次进展 2020-12-15 08:09

How can I have a unique validation rule on 2 fields?

a. The application should not allow two people to have the same identical first name and last name.

It i

5条回答
  •  北海茫月
    2020-12-15 08:21

    The built in unique validator wouldn't really support what you're trying to do. It's purpose is to ensure that a single valid is unique in the database, rather than a composite of two values. However, you can create a custom validator:

    Validator::extend('uniqueFirstAndLastName', function ($attribute, $value, $parameters, $validator) {
        $count = DB::table('people')->where('firstName', $value)
                                    ->where('lastName', $parameters[0])
                                    ->count();
    
        return $count === 0;
    });
    

    You could then access this new rule with:

    'firstName' => "uniqueFirstAndLastName:{$request->lastName}"
    

    You'll probably find you might need to tweak your database query a little bit as it's untested.

提交回复
热议问题