I did the obligatory composer dump autoload and artisan clear compiled which did not help with the ReflectionException.
How to make a custom FormRequest error response in Laravel 5.5
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.
Hey CU256,
I think this might help, after trying clay's approach, at first it didn't work (kept on getting the ReflectionException). That was because I was using the:
use Illuminate\Support\Facades\Validator;
So i changed it to:
use Illuminate\Contracts\Validation\Validator;
and my override method is:
protected function failedValidation(Validator $validator)
{
throw new HttpResponseException(response()->json($validator->errors(), 422));
}
Hope it helps.
Please or to participate in this conversation.