Laravel8 自定义 validate 响应

原因

在新某项目开发中遇到一个问题:laravel 的验证方法会自动处理验证响应
比如登录方法:

  public function login(Request $request)
  {
      $request->validate([
          'username' => 'required|string',
          'password' => 'required|string',
      ]);
  }

验证失败时响应:

// status 422
{
    "message": "The given data was invalid.",
    "errors": {
        "username": [
            "The username field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}
  • 当时和前端商议自定义 status 就是在http body 的json 中加一个code状态,每次响应都是http 200
  • 查阅资料后发现只要在 Exceptions 添加对应 exception 的处理方法就ok了

修改方法:

  • 修改文件:app/Exceptions/Hander.php
  • 在 function register() 中添加 renderable 方法
<?php

namespace AppExceptions;

use IlluminateFoundationExceptionsHandler as ExceptionHandler;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that are not reported.
     *
     * @var array
     */
    protected $dontReport = [
        //
    ];

    /**
     * A list of the inputs that are never flashed for validation exceptions.
     *
     * @var array
     */
    protected $dontFlash = [
        'password',
        'password_confirmation',
    ];

    /**
     * Register the exception handling callbacks for the application.
     *
     * @return void
     */
    public function register()
    {
        //
        // $this->renderable(function (CustomException $e, $request) {
        //     return response()->view('errors.custom', [], 500);
        // });
        $this->renderable(function (ValidationException $e, $request) {
            return response(['code' => ResultCode::PARAM_INVALID, "error" => $e->errors()]);
        });

    }
}


修改后响应:

// status:200
{
    "code": 10001,
    "error": {
        "username": [
            "The username field is required."
        ],
        "password": [
            "The password field is required."
        ]
    }
}
原文地址:https://www.cnblogs.com/zjhblogs/p/14338407.html