Laravel 5.5 Validation change format of response when validation fails

不问归期 提交于 2019-12-04 13:20:50

I guess as per laravel upgrade guide we should return HttpResponseException

protected function failedValidation(Validator $validator)
{
    $errors = $validator->errors();
        $response = new ResponseObject();

        $response->code = ResponseObject::BAD_REQUEST;
        $response->status = ResponseObject::FAILED;
        foreach ($errors as $item) {
            array_push($response->messages, $item);
        }

    throw new HttpResponseException(response()->json($response));
}

If you want to do this from the FormRequest classes, potentially something like this:

protected function buildResponse($validator)
{
    return response->json([
        'code' => ResponseObject::BAD_REQUEST,
        'status' => ResponseObject::FAILED,
        'messages' => $validator->errors()->all(),
    ]);
 }

protected function failedValidation(Validator $validator)
{
    throw (new ValidationException($validator, $this->buildResponse($validator));
}

That would add that response you are building to the validation exception. When the exception handler tries to render this it will check if response was set and if so it will use that response you passed instead of trying to convert the ValidationException to a response itself.

If you want 'ALL' validation exceptions to end up being rendered in this format I might just do this at the exception handler level, as the exception handler already has the ability to convert these exceptions to Json, so you could alter the format in the handler itself and basically not have to make any adjustments to the default FormRequest at all.

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;
    }

credit : Origianal Answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!