我正在构建一个API,当出现错误时所需的输出如下:
{
"success": false,
"messages" : [
{
"field is missing for example",
....
}
]
}
我从控制器调用了一个自定义请求,如下所示:
public function store(CoverageValueRequest $request, CoverageValueManager $manager){
$manager->create($request);
return response()->json(['success' => $manager->isSuccessful(), 'message' => $manager->getErrorMessage()]);
}
如果CoverageValueRequest
出现错误,则会发生与此类似的错误:
[
{
"series.0.values.0.cells": [
"The series.0.values.0.cells field is required when none of series.0.values.0.wifi are present."
],
"series.0.values.0.wifi": [
"The series.0.values.0.wifi field is required when none of series.0.values.0.cells are present."
]
}
]
如何修改自定义请求的错误结果以遵循第一个发布的结构。
提前致谢。
答案 0 :(得分:2)
您需要做的就是实现自己的failedValidation
方法。默认为
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException($this->response(
$this->formatErrors($validator)
));
}
实际上,您应该保持此方法不变并实现您自己的默认版本:
protected function formatErrors(Validator $validator)
{
return $validator->getMessageBag()->toArray();
}