1:通过php artisan make:request **** 创建自定义验证类,验证不通过后默认返回格式如下:
{"message":"The given data was invalid.","errors":{"type":["type\u4e0d\u80fd\u4e3a\u7a7a"]}}
有时候我们已经设置了全局的错误返回格式,这种格式对于我们用处不大
可以在自定义验证类中添加如下方法:
/**
* 验证失败
*/
public function failedeeValidation($validator)
{
$error=$validator->errors()->first();//单个错误
//$error=$validator->errors()->all(); //所有错误
$response = response()->json(['code'=>0,'msg'=>'fail','data'=>$error]);//这里可以自定义错误格式
throw new HttpResponseException($response);
}
2:手动创建的验证自定义返回格式如下
$param = $request->all();
$validator = Validator::make($param, [
'type' => 'required|unique:users,uid',
'unionid' => 'required|min:6|confirmed',
]);
if ($validator->fails()) {
$error=$validator->errors()->first();
$response=response()->json(['code'=>0,'msg'=>$error]);
throw new HttpResponseException($response);
}