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

时间:2019-04-29 10:57:21

标签: php laravel

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

3 个答案:

答案 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) {

}

相关问题