【发布时间】:2017-10-19 13:42:36
【问题描述】:
我正在使用 Laravel 5.4 并尝试在我的 POST 请求中验证 JSON,但是验证器未能指出 JSON 无效,即使它是有效的。我假设我没有正确理解验证规则并且我的实现是错误的,而不是错误或其他什么。
我有一个简单的 POST 端点,它的 Accept 和 Content-Type 标头都设置为 application/json。
在我的 POST 请求(使用 Postman 测试)中,我提供了 RAW 数据。
{
"only_this_key": { "one": "two" }
}
在我的控制器方法中,我有以下内容:
// I'm using intersect to remove any other parameters that may have been supplied as this endpoint only requires one
$requestData = $request->intersect(['only_this_key']);
$messages = [
'only_this_key.required' => 'The :attribute is required',
'only_this_key.json' => 'The :attribute field must be valid JSON',
];
$validator = \Validator::make($requestData, [
'only_this_key' => 'required|json',
], $messages);
if ($validator->fails()) {
return new APIErrorValidationResponse($request, $validator);
}
return response()->json(['all good' => 'here']);
我得到的错误是库存字段必须是有效的 JSON,即使它是!
使用 Postman 传递原始数据
{
"only-this-key": {
"item-one": "one",
"item-two": "two",
"item-three": "three"
},
"not": "wanted"
}
当我在方法中使用dd($request->all());时
array:2 [
"what-i-want" => array:3 [
"item-one" => "one"
"item-two" => "two"
"item-three" => "three"
]
"not" => "wanted"
]
【问题讨论】:
-
您真的需要将其作为原始数据发送吗?
-
是的,我只想要一个字段(正文),而不是单独的参数
-
你能在你的控制器中运行
dd($request->all())第一件事并发布它显示给你的内容吗? -
由于某种原因,Laravel 将值转换为 PHP 数组 - 很可能它在幕后调用
json_decode。因此,当它到达验证器时它不是有效的 JSON - 它是一个数组。我不知道为什么我在测试中没有看到相同的行为(甚至可能是 Postman 设置的不同)。当然,您可以在值上调用json_encode,它应该会通过,但我对 为什么 你会遇到这种行为感到困惑......
标签: json laravel-5.4 laravel-validation