Laravel Validation Error customise format of the Response

后端 未结 4 954
遇见更好的自我
遇见更好的自我 2020-12-17 01:42

I am working with L5 Form Requests and don\'t I just love Taylor! Well, I am doing some AJAX requests and I still want to retain my form requests. The problem is that in the

4条回答
  •  盖世英雄少女心
    2020-12-17 02:31

    This is inspired by this post and the answer by Shobi. Why not keep the transformErrors function from the Shobi's answer and simply modify the render function inside Handler.php? An example would look like:

    /**
     * Render an exception into an HTTP response.
     *
     * @param  Request  $request
     * @param Exception $exception
     * @return Response
     *
     * @throws Exception
     */
    public function render($request, Exception $exception)
    {
        if ($exception instanceof ValidationException) {
            return response()->json([
                'code' => $exception->status,
                'error' => $exception->getMessage(),
                'message' => $this->transformErrors($exception)
                ], $exception->status);
        }
        return parent::render($request, $exception);
    }
    

    This makes invalidJson function redundant and allows to add more fine-grained differentiation of custom json responses on each type of exception.

    Tested on Laravel 6.2

提交回复
热议问题