Laravel Validation Error customise format of the Response

后端 未结 4 944
遇见更好的自我
遇见更好的自我 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:30

    If you are in laravel 5+ you can easily achieve this, by overriding the invalid() or invalidJson() method in the App/Exceptions/Handler.php file

    In my case, I was developing an API and the api responses should be in a specific format, so I have added the following in the Handler.php file.

    /**
         * Convert a validation exception into a JSON response.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Illuminate\Validation\ValidationException  $exception
         * @return \Illuminate\Http\JsonResponse
         */
        protected function invalidJson($request, ValidationException $exception)
        {
            return response()->json([
                'code'    => $exception->status,
                'message' => $exception->getMessage(),
                'errors'  => $this->transformErrors($exception),
    
            ], $exception->status);
        }
    
    // transform the error messages,
        private function transformErrors(ValidationException $exception)
        {
            $errors = [];
    
            foreach ($exception->errors() as $field => $message) {
               $errors[] = [
                   'field' => $field,
                   'message' => $message[0],
               ];
            }
    
            return $errors;
        }
    

提交回复
热议问题