Php Laravel 5.3-验证脚手架如何插入错误
我对拉雷维尔比较陌生,试着理解一些事情。我创建了一个基本项目并使用` `php artisan make:auth `生成一个身份验证框架 在生成的视图中,$errors变量可用。我知道可以使用withErrors()方法将其插入到视图中 然而,我似乎无法找到如何将其插入示例中。在引擎盖下,以下功能似乎正在处理注册:Php Laravel 5.3-验证脚手架如何插入错误,php,laravel,laravel-5.3,laravel-facade,illuminate-container,Php,Laravel,Laravel 5.3,Laravel Facade,Illuminate Container,我对拉雷维尔比较陌生,试着理解一些事情。我创建了一个基本项目并使用` `php artisan make:auth `生成一个身份验证框架 在生成的视图中,$errors变量可用。我知道可以使用withErrors()方法将其插入到视图中 然而,我似乎无法找到如何将其插入示例中。在引擎盖下,以下功能似乎正在处理注册: /** * Handle a registration request for the application. * * @param \Illuminate\Ht
/**
* 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视图的。RegisterController扩展控制器,如果我们查看类控制器,我们可以看到使用trait
illighted\Foundation\Validation\validateRequests代码>
如果我们深入研究,我们会发现:
/**
* 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());
}
发生验证错误时,Laravel抛出异常。在这种情况下,将抛出ValidationException
的实例
Laravel使用其illighted\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);
}