laravellaravel-validationlaravel-request

Laravel validation errors if not using Validator facade


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?


Solution

  • 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.