Does formatErrors not working anymore in Laravel 5.5?

892 Views Asked by At

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?

1

There are 1 best solutions below

2
On BEST ANSWER

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