我正在使用验证器来验证请求参数并向公共API的用户返回有用的消息。如果验证器失败,我返回一个视图:
if( $validator->fails() ){
$data = ['errors' => $validator->errors()->messages() ];
return response()->view('errors.412', $data, 412)
->header("HTTP/1.0 412 Precondition Failed", null);
} else {
...
}
景色...
<ul>
@foreach( $errors as $field )
@foreach( $field as $error )
<li>{{ $error }}</li>
@endforeach
@endforeach
</ul>
因为这些消息将由开发人员使用,我希望它们是技术性的和具体的。因此,Laravel自动从我的参数键中剥离空间真的很烦人。
对于消息:
'The :attribute field is required.'
拉维尔回归:
车辆名称字段为必填项。
。但我想要更准确:
vehicle_name字段为必填字段。
我发现的唯一解决方法是将以下行添加到/resources/lang/en/validation.php
:
'attributes' => [
'vehicle_name' => 'vehicle_name'
],
但这只是感觉倒退,我必须在语言翻译文件中提供一堆相同的键对值,只是为了指示框架撤消不需要的行为。
有没有更好的方法?
这对我来说是最干净的方式:
$rules = [
'access_key1' => 'nullable|string|max:200',
'access_key2' => 'numeric',
'access_key3' => 'array',
];
$keys = array_keys($rules);
$customAttributes = array_combine($keys, $keys);
Validator::make($request->all(), $rules, [], $customAttributes);
答案来自我对我在 laravel/internals GitHub 存储库 https://github.com/laravel/internals 上发布的功能请求的评论
我在使用视图显示错误时走错了路。对于技术用户,以 JSON 格式返回错误是最合适的格式,在该上下文中,参数的特定键是可见的:
{
"message": "The given data was invalid.",
"errors": {
"vehicle_name": [
"The vehicle name field is required"
]
}
}
所以我更改了我的代码以在验证失败的情况下返回 JSON。
您可以为每个规则使用自己的消息:
$data = $request->all();
$messages= [
'access_key.required' => 'access_key is required, I'm technical x)',
'access_key.max' => 'Yooo! calm down! you exceded max characters limit'
];
$rules = [
'access_key' => 'required|max:255',
];
return Validator::make($data,$rules, $messages);
如果您没有为某些规则提供消息,它将使用默认消息(替换下划线)。
因此,这种方式就像为每个规则添加一个标志,但让您有机会重写整个消息并省略您不想提供特定消息的任何字段。