我正在用多种语言同时返回验证错误。
我有一个控制器,它注入了一个扩展FormRequest的类,我正在重写"failedValidation",在那里我得到了验证器错误消息。
public function store(SysUserStoreRequest $request)
{
// ...
}
class SystemUserStoreRequest extends ApiRequest
{
// This extends another class ApiRequest
Here I defined rules()
}
class APIRequest extends FormRequest
{
// Here I override the FailedValidation method.
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response($validator->getMessageBag()->toArray()));
}
}
上面的代码当前以默认语言返回错误。我可以通过更改中间件中的区域设置来更改响应以用不同的语言显示,但我正在处理需要返回一个新的验证错误结构的需求,其中en和fr中的每个字段都有错误。
我需要如下结构:
{
"detail": {
"email": {
"en-CA" : [
"The email has already been taken."
],
"fr-CA" : [
"The french text."
]
},
"first_name": {
"en-CA" : [
"The first name must be at least 5.",
"The first name must be an integer."
],
"fr-CA" : [
"The french text",
"The french text."
]
}
}
}
所以我厌倦了覆盖failedValidation方法,并做如下操作:
$validation_structure = [];
if ($validator->fails()) {
$failedRules = $validator->failed();
}
在获得所有失败的规则后,我可以从lang文件夹中获得每个区域设置的字符串,并获得字段和规则的字符串,然后使用生成消息
$x[] = __('validation.unique', [], 'fr-CA');
$x[] = __('validation.unique', [], 'en-CA');
这将为我提供两种语言的字符串,但我不知道如何替换:attributes、:values和其他各种字符串替换。
您可以覆盖SystemUserStoreRequest将返回的消息包以格式化消息。
class SystemUserStoreRequest extends ApiRequest
{
public function rules()
{
return [
'email' => 'required|unique:users,email,' . $this->id,
];
}
public function messages()
{
return [
'email.required' => [
'nl' => __('validation.required', ['attribute' => __('portal.email', [],'nl')], 'nl'),
'en' => __('validation.required', ['attribute' => __('portal.email', [],'en')], 'en'),
],
'email.unique' => [
'nl' => __('validation.unique', ['attribute' => __('portal.email', [],'nl')], 'nl'),
'en' => __('validation.unique', ['attribute' => __('portal.email', [],'en')], 'en'),
]
];
}
}
然后输出看起来像:
{
"message":"The given data was invalid.",
"errors":{
"email":[
{
"nl":"E-mailadres is verplicht.",
"en":"The email field is required."
}
]
}
}
以下是有关自定义消息的更多文档:https://laravel.com/docs/8.x/validation#specifying-语言文件中的自定义消息