我有两个数组要在我的自定义 Request
中验证:
$rules = [
'params.words1.*.value' => 'required|string|between:5,50',
'params.words2.*.value' => 'required|string|between:5,50',
];
这将返回每个单词的错误消息。但我想要一个单一的一般信息,比如“有些词是无效的”。
有没有 Laravel 的方式来做到这一点?
最佳答案
你可以这样做:
$messages = [
'params.*' => 'Some of the words are invalid.',
];
编辑:
我想我可能已经找到了解决方案:
首先,确保在顶部导入 Validator 和 HttpResponseException:
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
然后,您可以覆盖 native
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
));
}
关于php - 合并验证错误并返回一条消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49824847/