如何在Laravel 5.6中验证两个字段的组合唯一性?

时间:2018-07-27 12:15:28

标签: laravel validation laravel-5.6 laravel-validation

这是我的验证规则:-

$validationCondition    = array(
                            'fname'     => 'required|min:2',
                            'lname'     => 'required|min:2',
                            'email'     => 'required|email|unique:users,email',
                            'isd'       => 'required|unique:users,isd',
                            'mobile'    => 'required',
                            'password'  => 'required'
                        );
$validationMessages     = array(
                            'fname.required'    => 'Please provide first name',
                            'fname.min'         => 'First name should be atleast 3 characters long',

                            'lname.required'    => 'Please provide last name',
                            'lname.min'         => 'Last name should be atleast 3 characters long',

                            'email.required'    => 'Please provide email',
                            'email.email'       => 'Please provide a valid email id',
                            'email.unique'      => 'This email id has already been registered. Choose any other valid email id.',

                            'isd.required'      => 'The city name should be atleast 3 characters long',

                            'mobile.required'   => 'Please provide mobile number',

                            'password.required' => 'Please provide password'
                        );

在用户表中,要同时检查 isd 手机,以确保联系人号码是否唯一。

如何检查?我知道如何检查单个字段的唯一性,但不知道如何将组合值检查为唯一。

2 个答案:

答案 0 :(得分:3)

$validationCondition = array(
    ...
    'isd' => 'required',
    'mobile' => 'required|unique:users,mobile,NULL,id,isd,' . $request->isd,
    ...
);

unique的{​​{1}}规则的含义将是:“ mobile的值在所有mobile都具有相同值的现有用户中必须是唯一的应要求”。

isd这里是您正在验证的传入请求的实例(显然)。

答案 1 :(得分:1)

您可以像下面那样使用

'mobile'  => 'required|unique:users,mobile,NULL,id,mobile,isd'

获取更多详细信息from doc