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 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C