验证后如何在 Laravel 控制器中捕获和 return 错误?

How to catch and return errors in Laravel controller after validation?

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

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

在此之后我想 return 错误消息作为 JSON 对象,使用此代码:

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

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

有什么想法吗?

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

https://laravel.com/docs/5.7/validation#customizing-the-error-messages https://laravel.com/docs/5.7/validation#working-with-error-messages

$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);

希望能帮到你