When we use Laravel Form Requests in our controllers and the validation fails then the Form Request will redirect back with the errors
variable.
How can I disable the redirection
and return a custom error response when the data is invalid?
I'll use form request to GET|POST|PUT
requests type.
I tried the Validator
class to fix my problem but I must use Form Requests.
$validator = \Validator::make($request->all(), [
'type' => "required|in:" . implode(',', $postTypes)
]);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()]);
}
Creating custom FormRequest
class is the way to go.
namespace App\Http\Requests;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Validation\ValidationException;
use Illuminate\Http\Exceptions\HttpResponseException;
class FormRequest extends \Illuminate\Foundation\Http\FormRequest
{
protected function failedValidation(Validator $validator)
{
if ($this->expectsJson()) {
$errors = (new ValidationException($validator))->errors();
throw new HttpResponseException(
response()->json(['data' => $errors], 422)
);
}
parent::failedValidation($validator);
}
}
Class is located in app/Http/Requests
directory. Tested & works in Laravel 6.x.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With