Laravel,将值附加到自定义请求错误消息

时间:2016-05-23 17:36:04

标签: php laravel laravel-5 laravel-request

我正在构建一个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."
    ]
}
]

如何修改自定义请求的错误结果以遵循第一个发布的结构。

提前致谢。

1 个答案:

答案 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();
}