POV
POV

Reputation: 12005

Validate POST request Laravel?

I validate POST request like:

$validator = Validator::make($request->all(), [
            "id.*" => 'required|integer'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors, 400);
        }

        echo "Ok";

When I send request without parameter id it skips validation and returns echo "Ok";.

Why validation does not work?

Upvotes: 2

Views: 8682

Answers (2)

Mohamed Allal
Mohamed Allal

Reputation: 20840

First know when using $request->validate(); when it fail exceptions are raised! And they are automatically handled by laravel. If it's a get, or a normal post form, then the process will redirect back to the form.

To note, when using the validate method during an AJAX request, Laravel will not generate a redirect response. Instead, Laravel generates a JSON response containing all of the validation errors. This JSON response will be sent with a 422 HTTP status code.

If you want to not have such an automatic behavior, create manually a validator, then you can check with ->fails() method, as the example show bellow. That's can be handful in a lot of situations.

<?php 
public function store(Request $request)

        {
            $validator = Validator::make($request->all(), [
                'title' => 'required|unique:posts|max:255',
                'body' => 'required',
            ]);

            if ($validator->fails()) {
                return redirect('post/create')
                            ->withErrors($validator)
                            ->withInput();
            }

            // Store the blog post...
        }
    }

And there is no better then the doc itself: https://laravel.com/docs/5.7/validation there is a lot of options, to personalize our validation process.

Upvotes: 1

Marcin Nabiałek
Marcin Nabiałek

Reputation: 111829

If you expect id is array of integers you should update validation rules like this:

$validator = Validator::make($request->all(), [
            "id" => 'required|array',
            "id.*" => 'integer'
        ]);

Upvotes: 4

Related Questions