0

I have this code for an API, testing with Postman:

public function register(Request $request)
{
    $validated = $request->validate([
        'name' => 'required|string',
        'email' => 'required|string|unique:users,email',
        'password' => 'required|string|confirmed'
    ]);

    if($validated->fails()){
        dd($validated->errors()->toArray());
    }

    $validated = Validator::make($request->all(), [
        'name' => 'required|string',
        'email' => 'required|string|unique:users,email',
        'password' => 'required|string|confirmed'
    ]);

    if ($validated->fails()) {
        $errors = $validated->errors()->toArray();
        dd($errors);
    }
}

I haven't included at all the password_confirmation field in the request.

Validation fails, as it should, but the first dd statement doesn't get printed and Postman shows the homepage.

If I comment the part using the validate method on the $request and leave only the part that uses Validator facade, dd works as it should, saying The password field confirmation does not match.

Is it possible to debug if it fails using $request->validate instead of the Validator facade?

1 Answer 1

1

It's not actually showing the home page; it's redirecting the user back to the previous page (which happens to be the home page, I suspect; if you look at your browser's network panel you'll see a 302 redirect), with validation errors in the session. Your code never gets to the dd() call as a result.

https://laravel.com/docs/10.x/validation

So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.

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

3 Comments

I'm testing in Postman, is there any way to see the validation errors there? As I said, it's an API, I can't test in the browser, at least I don't know how to make POST requests and provide bearer tokens into the browser.
@alex Send a header of Accept: application/json in the Postman request and it'll give a JSON response instead of the redirect.
the header worked, thanks!

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.