如何在Laravel中进行多字段唯一验证?

时间:2018-06-29 05:28:27

标签: php laravel validation

所有其他验证工作正常,但我必须验证 国家/地区代码为唯一的手机号码并生成自定义验证消息。请帮帮我。

    $validator = Validator::make($request->all(), [
        'first_name'=> 'required|min:2|max:30',
        'last_name' => 'required|min:2|max:30',
        'email'     => 'required|unique:users,email,'.$userId,
        'mobile'    => 'required|numeric|min:10|unique:users,mobile,'.$userId,
    ]);
if ($validator->fails()){
            $response['status'] = "false"; 
            $response['message'] = $this->validationHandle($validator->messages());  
            $response['data'] = []; 
            $this->response($response);
        }else{
//true function response
}

2 个答案:

答案 0 :(得分:0)

您可以为这种情况创建自己的验证器:

  Validator::extend('custom_unique',

         function ($attribute, $value, $parameters, $validator) {

         // Get table name from first parameter
            $table = array_shift($parameters);

        // Build the query
           $query = DB::table($table);

       // Add the field conditions
          foreach ($parameters as $i => $field) {
            $query->where($field, $validator->getData()[$field]);
          }

      // Validation result will be false if any rows match the combination
          return ($query->count() == 0);

   });

您可以使用它:

 //table_name - users 
 //fields -  user_id,mobile_no,etc..
'mobile' => 'required|numeric|min:10|custom_unique:users,user_id,mobile_no'...

答案 1 :(得分:0)

首先在控制器顶部添加Rule类,然后针对移动设备进行如下更改验证。

use Illuminate\Validation\Rule;
    $validator = Validator::make($request->all(), [
            'first_name'        => 'required',
            'last_name'         => 'required',
            'email'             => 'required|unique:users',
            'mobile'            => ["required","numeric","min:7",Rule::unique('users')->where(function ($query)use ($request) {
                                        return $query->where('country_id',"=", $request->country_id);
                                    })],
            'country_id'        => 'required|numeric',
            'password'          => 'required|min:8|max:15',
            'account_type'      => 'required',
            'device_type'       => 'required',
            'device_token'      => 'required',
        ]); 

希望如此,您将获得正确的答案。 (y)