phplaravellaravel-5.3laravel-facadeilluminate-container

Laravel 5.3 - Auth Scaffolding How Are Errors Inserted


Im relatively new to Laravel and try to make sense of something. I created a basic project and used `

` php artisan make:auth

` to generate a authentication scaffolding.

In the generated views, the $errors variable is available. I know that this can be inserted into a view by using the withErrors() method.

However, I can't seem to find how this is inserted in the example. Under the hood the following function seems to be handling registration:

    /**
 * Handle a registration request for the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function register(Request $request)
{
    $this->validator($request->all())->validate();

    event(new Registered($user = $this->create($request->all())));

    $this->guard()->login($user);

    return $this->registered($request, $user)
                    ?: redirect($this->redirectPath());
}

So the validator method of the default RegisterController is called, and it returns a validator. But i cannot grasp how the errors from the validator are inserted into the auth.register view.


Solution

  • What happens when a validation error occurs is that Laravel throws an exception. In this case an instance of ValidationException is thrown.

    Laravel handles any uncaught exception using it's Illuminate\Foundation\Exceptions\Handler class. In your app you should see a class that extends it in app/Exceptions/Handler.php. In that class you will see that the render method calls it's parent's render method which if you check the code contains the following lines:

    public function render($request, Exception $e)
    {
        $e = $this->prepareException($e);
    
        if ($e instanceof HttpResponseException) {
            return $e->getResponse();
        } elseif ($e instanceof AuthenticationException) {
            return $this->unauthenticated($request, $e);
        } elseif ($e instanceof ValidationException) {
            return $this->convertValidationExceptionToResponse($e, $request);
        }
    
        return $this->prepareResponse($request, $e);
    }
    

    And if you check further in that same class, in the method convertValidationExceptionToResponse you can see that Laravel flashes the errors to the response and redirects back, with the input (When the request doesn't expect JSON):

    protected function convertValidationExceptionToResponse(ValidationException $e, $request)
    {
        if ($e->response) {
            return $e->response;
        }
    
        $errors = $e->validator->errors()->getMessages();
    
        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }
    
        return redirect()->back()->withInput($request->input())->withErrors($errors);
    }