laravel-5laravel-5.5laravel-validationlaravel-response

Does formatErrors not working anymore in Laravel 5.5?


I have following code in my Request class that returns custom messages.

public function formatErrors(\Illuminate\Contracts\Validation\Validator $validator) {
    if($validator->fails()) {
        $validator->errors()->add('Message', "Validation failed");
    }
    return parent::formatErrors($validator);
}

It was returning the error messages in Laravel 5.4 but seems like this function is no more working in Laravel 5.5

Did anybody face this issue in Laravel 5.5?


Solution

  • In Upgrade guide you can read:

    In Laravel 5.5, all exceptions, including validation exceptions, are converted into HTTP responses by the exception handler. In addition, the default format for JSON validation errors has changed. The new format conforms to the following convention: ...

    So what you should do is add to app\Exceptions\Handler.php file the following method:

    protected function invalidJson($request, ValidationException $exception)
    {
        return response()->json([
            'message' => 'Validation failed',
            'errors' => $exception->errors(),
        ], $exception->status);
    } 
    

    obviously you might want to adjust this method more because in previous Laravel versions it was by default like this:

    return response()->json($exception->errors(), $exception->status);