根据usertype设置laravel验证器

时间:2017-10-14 15:58:50

标签: php laravel

CREATE TABLE TT
(
 WorkDate DATE,
 FromTime VARCHAR2(100 BYTE),
 ToTime   VARCHAR2(100 BYTE)

)

Work date   From    To
8/8/2017    7:00    7:25
8/8/2017    7:25    12:35
8/8/2017    12:35   21:55
8/8/2017    21:55   1:30
8/8/2017    1:30    7:00
8/9/2017    7:00    7:25
8/9/2017    7:25    12:35
8/9/2017    12:35   21:55
8/9/2017    21:55   1:30
8/9/2017    1:30    7:00

如何根据用户类型设置验证器?我确实尝试过不行。

2 个答案:

答案 0 :(得分:4)

按用户类型添加规则数组并最后放置规则

$rules = [
    'first_name' => 'required|min:3',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
    'password_confirmation' => 'required',
    'address' => 'required',
    'phone_number' => 'required',
];

if($request->user_type == 1 ){
    $rules['dob'] =  'required';
}else if($request->user_type == 2 ){
    $rules['doctor_practice'] =  'required';
}

$validator = \Validator::make($request->all(), $rules);
if ($validator->fails()) {    
    return response()->json($validator->messages(), 401);
}

答案 1 :(得分:1)

使用嵌入式验证机制更好,更正确。

$rules = [
    'first_name' => 'required|min:3',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:6|confirmed',
    'password_confirmation' => 'required',
    'address' => 'required',
    'phone_number' => 'required',
    'dob' => 'required_if:user_type,1',
    'doctor_practice' => 'required_if:user_type,2',
];

$validator = \Validator::make($request->all(), $rules);
if ($validator->fails()) {    
    return response()->json($validator->messages(), 401);
}

Laravel documentation

中对此进行了描述
  

required_if:anotherfield,值,...

     

如果anotherfield字段等于任何值,则验证字段必须存在且不为空。