合并验证错误并返回单个消息

时间:2018-04-13 20:41:57

标签: php laravel laravel-5

我想在自定义array中验证两个数组:

Request

这会返回每个单词的错误消息。但我想要一个像“有些单词无效”这样的通用信息。 有没有Laravel的方法呢?

2 个答案:

答案 0 :(得分:2)

您是否尝试过保释参数?

https://laravel.com/docs/5.6/validation

这应该只返回第一个验证错误,如果您的所有规则都有相同的验证错误消息,这将获得所需的结果。

编辑:这是为了Laravel 5.2及以上。

答案 1 :(得分:1)

你可以这样做:

$messages = [
    'params.*' => 'Some of the words are invalid.',
];

编辑:

我想我可能找到了解决方案:

首先,确保在顶部导入Validator和HttpResponseException:

use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;

然后,您可以覆盖原生failedValidation方法并根据需要更改错误:

protected function failedValidation(Validator $validator)
{
    // Get all the errors thrown
    $errors = collect($validator->errors());
    // Manipulate however you want. I'm just getting the first one here,
    // but you can use whatever logic fits your needs.
    $error  = $errors->unique()->first();

    // Either throw the exception, or return it any other way.
    throw new HttpResponseException(response(
        $error,
        422
    ));
}
相关问题