【问题标题】:How to catch and return errors in Laravel controller after validation?验证后如何在 Laravel 控制器中捕获并返回错误?
【发布时间】:2018-10-26 20:51:14
【问题描述】:

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

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

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

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

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

有什么想法吗?

【问题讨论】:

    标签: validation laravel-5.7 error-messaging


    【解决方案1】:

    如果你需要自定义错误信息,只需要阅读 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);
    

    希望能帮到你。

    【讨论】:

      猜你喜欢
      • 2019-07-03
      • 1970-01-01
      • 2020-06-04
      • 2019-03-30
      • 2020-04-09
      • 2016-05-21
      • 2018-04-30
      • 2014-12-22
      • 2015-11-20
      相关资源
      最近更新 更多