11

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()]);
}
4

5 Answers 5

19

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I've finally found your answer, exactly what I need.
Thanks for this answer. Is there a way to do this globally for all form requests? Or in a midlleware?
@Nebster You can just extend this class in your other form request classes.
1

This is the same but written differently:

protected function failedValidation(Validator $validator)
{
    $errors = (new ValidationException($validator))->errors();

    throw new HttpResponseException(
        response()->json([
            'message' => "",
            'errors' => $errors
        ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
    );
}

Comments

0

Base class FormRequest has method failedValidation. Try to override it in your FormRequest descendant

use Illuminate\Contracts\Validation\Validator;

class SomeRequest extends FormRequest
{
    ...

    public function failedValidation(Validator $validator)
    {
        // do your stuff
    }
}

11 Comments

Error message: Declaration of App\Http\Requests\PostCreate::failedValidation(App\Http\Requests\Validator $validator) should be compatible with Illuminate\Foundation\Http\FormRequest::failedValidation(Illuminate\Contracts\Validation\Validator $validator)
it seems you didn't add use of Validator
I've use Validator and also tired \Validator but not work
you should use concrete use Illuminate\Contracts\Validation\Validator;
I want validate data using Form Requests inside API routes and return errors instead of redirect. @Roman Bobrik
|
0

use this on function dont forget to take on top // use App\Http\Requests\SomeRequest;

$validatedData = $request->validated();
\App\Validator::create($validatedData);

create request php artisan make:request SomeRequest ex. use Illuminate\Contracts\Validation\Validator;

class SomeRequest extends FormRequest
{
   public function rules()
    {
        return [
            'health_id'      => 'required',
            'health'         => 'required',
        ];
    }
 
}

Comments

0

Add this function to your custom request:

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Http\Exceptions\HttpResponseException;
use Illuminate\Http\JsonResponse;

protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(
        response()->json([
            'errors' => $validator->errors(),
        ], JsonResponse::HTTP_UNPROCESSABLE_ENTITY)
    );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.