laravel 在视图中循环验证错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21963327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Looping through validation errors in view
提问by John Dorean
I'm using Laravel's form validation functionality and trying to work out how I can loop through the form errors in my view. At the moment, I'm successfully validating the form using the below code:
我正在使用 Laravel 的表单验证功能,并试图找出如何在我的视图中循环遍历表单错误。目前,我正在使用以下代码成功验证表单:
public function create()
{
$validator = Validator::make(
Input::all(),
array(
'username' => 'required|alpha_num|unique:users',
'email' => 'email|unique:users',
'password' => 'required|min:6',
'passwordConf' => 'required|same:password'
)
);
if ($validator->fails())
{
return Redirect::to('join')->withErrors($validator);
}
return View::make('user/join')->with();
}
The validator successfully validates the form and redirects to the join
route if validation fails. Obviously, I'd also like to show the validation messages to the user. I have a master.blade.php
layout file which all of my views extend, and in the layout I have the following code:
验证器成功验证表单并join
在验证失败时重定向到路由。显然,我还想向用户显示验证消息。我有一个master.blade.php
布局文件,我的所有视图都扩展了它,在布局中我有以下代码:
@if (Session::has('errors'))
<div class="alert alert-danger">
@foreach (Session::get('errors') as $error)
Test<br />
@endforeach
</div>
@endif
This seems to half work. If there are validation errors, the alert div does show on the page, however no validation errors get output. That suggests that Session::has('errors')
is returning true however I'm obviously not iterating through the validation errors correctly.
这似乎成功了一半。如果存在验证错误,警报 div 会显示在页面上,但不会输出验证错误。这表明Session::has('errors')
返回 true 但我显然没有正确迭代验证错误。
How do I iterate through the validation errors sent to the view via withErrors
?
如何遍历通过 发送到视图的验证错误withErrors
?
回答by Joseph Silber
There's an automatic $errors
variable passed to your view. You don't have to check the session directly.
有一个自动$errors
变量传递给您的视图。您不必直接检查会话。
@foreach ($errors->all() as $error)
{{ $error }}<br/>
@endforeach
Here's a quote from the docs:
这是文档中的引用:
Notice that we do not have to explicitly bind the error messages to the view in our GET route. This is because Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that an
$errors
variable will always be available in all of your views, on every request, allowing you to conveniently assume the$errors
variable is always defined and can be safely used. The$errors
variable will be an instance ofMessageBag
.
请注意,我们不必将错误消息显式绑定到 GET 路由中的视图。这是因为 Laravel 将始终检查会话数据中的错误,并在它们可用时自动将它们绑定到视图。因此,重要的是要注意一个
$errors
变量将始终在您的所有视图中可用,在每个请求中,允许您方便地假设该$errors
变量始终已定义并且可以安全使用。该$errors
变量将是 的一个实例MessageBag
。