我对Laravel相对较新,并尝试理解某些事情。我创建了一个基本项目并使用了`
`php artisan make:auth
`生成身份验证脚手架。
在生成的视图中,$ errors变量可用。我知道可以使用withErrors()方法将其插入到视图中。
但是,我似乎无法在示例中找到它的插入方式。在幕后,以下功能似乎是处理注册:
/**
* 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());
}
因此调用默认RegisterController的validator方法,并返回验证器。但是我无法理解如何将验证器中的错误插入到auth.register视图中。
答案 0 :(得分:1)
发生验证错误时会发生的事情是Laravel抛出异常。在这种情况下,抛出ValidationException
的实例。
Laravel使用Illuminate\Foundation\Exceptions\Handler
类处理任何未捕获的异常。在您的应用中,您应该会看到一个在app/Exceptions/Handler.php
中扩展它的类。在该类中,您将看到render
方法调用它的父级render
方法,如果您检查代码包含以下行:
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);
}
如果你在同一个类中进一步检查,在方法convertValidationExceptionToResponse
中你可以看到Laravel将错误闪烁到响应并重定向回来,输入(当请求不期望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);
}
答案 1 :(得分:0)
RegisterController扩展了Controller,如果我们看一下类控制器,我们可以看到使用trait Illuminate\Foundation\Validation\ValidatesRequests;
如果我们深入了解,我们会发现:
/**
* Create the response for when a request fails validation.
*
* @param \Illuminate\Http\Request $request
* @param array $errors
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}