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 App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler 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."
        ]
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM