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 Jenkins+k8s部署slave节点offline
  • ¥15 微信小游戏反编译后,出现找不到分包的情况
  • ¥15 如何实现从tello无人机上获取实时传输的视频流,然后将获取的视频通过yolov5进行检测
  • ¥15 WPF使用Canvas绘制矢量图问题
  • ¥15 用三极管设计一个单管共射放大电路
  • ¥15 孟德尔随机化r语言运行问题
  • ¥15 pyinstaller编译的时候出现No module named 'imp'
  • ¥15 nirs_kit中打码怎么看(打码文件是csv格式)
  • ¥15 怎么把多于硬盘空间放到根目录下
  • ¥15 Matlab问题解答有两个问题