Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return custom response when validation has fails using laravel form requests

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()]);
}
like image 405
Andreas Hunter Avatar asked Jun 04 '19 06:06

Andreas Hunter


1 Answers

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.

like image 55
N'Bayramberdiyev Avatar answered Sep 24 '22 22:09

N'Bayramberdiyev