Laravel Validator :: make vs this-> validate() [英] Laravel validator::make vs this->validate()

查看:369
本文介绍了Laravel Validator :: make vs this-> validate()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有一个验证器,该验证器工作正常(请参阅下文).

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

Laravel文档使用的Validator::make($request...)在良好实践和性能方面哪个更好?我使用的方法来自Laravel 5 Youtube教程系列.

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.

推荐答案

如果使用$validator = Validator::make(...,则必须检查验证是否失败或通过if ($validator->fails()) {...,然后手动返回控制器的响应.因此,如果您要重定向到某个地方,在呈现视图之前进行一些操作,对错误进行某种处理或在从该方法返回响应之前要执行任何其他操作,这将很有用.

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.

可用于所有控制器的 validate()方法将根据您提供的数据和规则自动检查验证是否失败.如果验证失败,则会抛出一个 ValidationException ,该异常将被自动处理,并且请求将重定向并返回验证中的错误.因此,如果您具有标准验证功能,并且只想验证并在视图中显示错误,这将非常有用.

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 ValidationException is 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.

这篇关于Laravel Validator :: make vs this-&gt; validate()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆