Laravel 验证器::make vs this->validate()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38874269/
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
Laravel validator::make vs this->validate()
提问by louisav
I have a validator in my controller which works fine (see below).
我的控制器中有一个验证器,它工作正常(见下文)。
$this->validate($request,[
'name' => 'required|alpha',
'sport' => 'required|alpha',
'gender' => 'required|alpha',
'age' => 'required|numeric',
'score' => 'required|numeric',
]);
When I get to my view, I just run this:
当我看到我的观点时,我只是运行这个:
@if(count($errors) > 0)
<div>
<ul>
@foreach($errors->all() as $error)
{{ $error }}
@endforeach
</ul>
</div>
@endif
The Laravel documentation uses Validator::make($request...)
which one is better in terms of good practice and also performance? The method I used comes from a Laravel 5 Youtube tutorial series.
Laravel 文档使用Validator::make($request...)
哪一种在良好实践和性能方面更好?我使用的方法来自 Laravel 5 Youtube 教程系列。
回答by thefallen
If you use $validator = Validator::make(...
you then have to check if the validation fails or passes if ($validator->fails()) {...
and manually return a response from the controller. So this is useful if you want to redirect somewhere, do something before rendering the view, do something with the errors or any other action you want to perform before returning a response from the method.
如果使用$validator = Validator::make(...
,则必须检查验证是否失败或通过if ($validator->fails()) {...
并手动从控制器返回响应。因此,如果您想重定向某个地方,在渲染视图之前执行某些操作,对错误执行某些操作或在从方法返回响应之前要执行的任何其他操作,这将非常有用。
The validate()method which is available to all controllers will automatically check if the validation fails based on the data and the rules you provided. If the validation fails a ValidationExceptionis thrown which is automatically handled and the request redirects back with the error from the validation. So this is useful if you have a standard validation and you want to just validate and show the errors in the view.
可用于所有控制器的validate()方法将根据您提供的数据和规则自动检查验证是否失败。如果验证失败,则会抛出ValidationException,该异常会被自动处理,并且请求会重定向回验证中的错误。因此,如果您有标准验证并且只想验证并在视图中显示错误,这将非常有用。