抛出验证异常显示给定数据无效



我正在使用 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()

使用它获取所有验证错误消息

$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();]);
}

如果您使用的是 laravel 5.8,则可以创建像 FilenameRequest.php by 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) {
}
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);
                   }

最新更新