如何在验证后捕获并返回Laravel控制器中的错误



我正在使用此代码验证我的$request变量:

$validatedData = $request->validate([
'name' => 'string|required|max:255',
'lead' => 'nullable|string',
...
]);

之后,我想将错误消息作为JSON对象返回,使用以下代码:

return response()->json([
'errors' => $validatedData->errors()
]);

这里说$ValidateData是一个数组。确实如此,但在哪里可以找到验证错误消息?我查看了官方的Laravel 5.7文档,但不清楚。

知道吗?

如果您需要自定义错误消息,只需要在laravel文档中阅读即可。

https://laravel.com/docs/5.7/validation#customizing-错误消息https://laravel.com/docs/5.7/validation#working-带有错误消息

$messages = [
'same'    => 'The :attribute and :other must match.',
'size'    => 'The :attribute must be exactly :size.',
'between' => 'The :attribute value :input is not between :min - :max.',
'in'      => 'The :attribute must be one of the following types: :values',
];
$validator = Validator::make($input, $rules, $messages);

我希望我能帮你。

最新更新