dousuie2222 2015-12-13 06:59
浏览 32
已采纳

Laravel 5.x(主)表单请求验证响应为json

Is there a way to return Form Request erros as a json?

I am making an API to AngularJS, and I am having problems with the error flags

Here is my rules:

class CreateProductRequest extends Request
{
    public function rules()
    {
    return [
            'code'=>'required|unique:products',
            'style'=>'required|max:12',
            'measure'=>'required|max:12',
        ];
    }

This is the response from CreateProductRequest

{
    code: [0: "Code is required"],
    style:[0: "Style is required"],
    measure:[ 0: "Measure is required"]
}

I want the same result as $validator->errors()->all() on the controller, like this:

"messages": [
    "Code is required",
    "Style is required",
    "Measure is required"
]

How can I get this result from Form Request?

Laravel version: master

  • 写回答

2条回答 默认 最新

  • dongyan7851 2015-12-13 12:17
    关注

    Form Request errors are already returned as json for AJAX requests. But to achieve the structure you want, you have to override the response function in vendor/laravel/framework/src/Illuminate/Foundation/Http/FormRequest.php

    Copy the function from there and paste it in Request class in app/Http/Requests/Request.php. Change the following line:

        return new JsonResponse($errors, 422);
    

    to this:

        $messages = array();
        foreach ($errors as $element) {
            foreach ($element as $element_error) {
                $messages[] = $element_error;
            }
        }
        $response['messages'] = $messages;
        $response['status'] = 'error';
        return new JsonResponse($response, 200);
    

    Instead of 200, you can return any other status code you are using already, maybe from 4xx series. Add this at the top of this file:

    use Illuminate\Http\JsonResponse;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计