我正在使用laravel 5.8,我想捕获带有验证异常的验证错误,这是我的代码:
$attr = $request->data['attributes'];
$validator = Validator::make($attr,[
'nama' => 'required|string',
'scope' => 'required|string'
]);
try{
if($validator->fails()){
//$err = ValidationException::withMessages($validator->errors()->getMessages());
throw new ValidationException($validator);
}
}catch(ValidationException $e){
return response()->json([
'status'=> 'error',
'code' => 400,
'detail' => $e->getMessage()
], 400);
}
但是它没有显示验证错误消息,只是显示“给定的数据无效”。
详细信息应为:
detail:[
'scope':['Scope field is required']
]
已修复更新:
只需致电$e->errors()
答案 0 :(得分:0)
Try this Code
$validator = Validator::make($request->all(), [
'nama' => 'required|string',
'scope' => 'required|string'
]);
if ($validator->fails()) {
return response()->json([
'status' => false,
'ErrorCode' => 1,
'error' => $validator->errors()],
400);
}
答案 1 :(得分:0)
使用它来获取所有验证错误消息
$validator = Validator::make($request->all(), [
'nama' => 'required|string',
'scope' => 'required|string'
]);
if ($validator->fails()) {
return response()->json([
'status' => false,
'ErrorCode' => 1,
'error' => $validator->errors()->messages();]);
}
答案 2 :(得分:0)
如果您使用的是laravel 5.8,则可以创建FilenameRequest.php
之类的php artisan make:request FilenameRequest
之类的独立验证文件
创建请求文件后,您的请求文件如下所示:
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'scope' => 'required|max:3',
];
}
public function messages()
{
return [
'scope' => 'Scope field is required'
];
}
在您的控制器方法中,您可以像这样简单地使用此请求文件
public function store(FilenameRequest $request) {
}