cu256
2 years ago
1706
9
Laravel

How to make a custom FormRequest error response in Laravel 5.5

Posted 2 years ago by cu256

Hello,

I am using FormRequests to validate data, but want to return custom JSON on error. So far I was extending the FormRequest and overriding the response method. But this stopped working with the update to 5.5. What is the current intended way to return a custom response on error?

What I tried is to override the failedValidation method and put my response into a ValidationException, however in this case a ReflectionException is thrown, because my Request class is not found.

What is the correct way to create a custom response in laravel 5.5?

Laravel 5.4

abstract class ApiFormRequest extends FormRequest
{
    public function response( array $errors ) {
        $json = [
            'status' => 'input_error',
            'errors' => 'more data'
        ];
        return new JsonResponse( $json, 400 );
    }
}

What I tried

public function failedValidation(Validator $validator)
{
    $json = [
        'status' => 'input_error',
        'errors' => 'more data'
    ];
    $response = new JsonResponse( $json, 400 );
    throw (new ValidationException($validator, $response))->status(400);
}

But throws ReflectionException in line 25 in /var/www/vendor/laravel/framework/src/Illuminate/Routing/RouteSignatureParameters.php

"Class App\Http\Requests\MyApp\Api\Page1Request does not exist"

Page1Request extends ApiFormRequest and definitely exists, because it works when I comment out the override method.

Please sign in or create an account to participate in this conversation.