Laravel 5.6 $this->validate vs Validator::make()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51194288/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:52:30  来源:igfitidea点击:

Laravel 5.6 $this->validate vs Validator::make()

phplaravelvalidation

提问by Striker

I saw there are a few other questions in which they asked what the difference was between $this->validateand Validator::make(). They didnt really answer the conceptual question I was wondering though.

我看到还有其他一些问题,他们询问了$this->validate和之间的区别Validator::make()。他们并没有真正回答我想知道的概念性问题。

Is there a proper use for each of these? Like when to use one versus the other?

这些都有正确的用途吗?比如什么时候使用一个和另一个?

How I am currently using it is in my API classes I use a if else with $validator::make()(like below) while in my Web portion of the program I use $this->validate()(also below)

我目前如何使用它是在我的 API 类中我使用 if else with $validator::make()(如下所示),而在程序的 Web 部分中我使用 $ this->validate()(也在下面)

Is this a proper way to use this?

这是使用它的正确方法吗?

$validator::make:

$validator::make:

public function store(Request $request)
    {
        $validator = Validator::make($request->all(),[
            'name' => 'required',
            'url' => 'required',
            'isPublic' => 'required'
        ]);

        if($validator->fails()){
            return response($validator->messages(), 200);
        } else {

            Helpers::storeServer($request);

            return response()->json([
                'message'=> ['Server Stored']
            ]);
        }
    }

$this->validate:

$this->验证:

 public function store(Request $request)
    {

        $this->validate($request, [
            'name' => 'required',
            'url' => 'required',
            'isPublic' => 'required'
        ]);

        Helpers::storeServer($request);

        return redirect('dashboard')->with('success', 'Server stored');
    }

回答by N Mahurin

Nope, they do the same exact thing two different ways. I mean that literally, $this->validate()calls the make()method on the validation class. If you look at ValidatesRequests.php, implemented by controller.php which your controller extends. The validate()method calls:

不,他们以两种不同的方式做同样的事情。我的意思是,从字面上看,$this->validate()调用make()验证类上的方法。如果您查看 ValidatesRequests.php,由您的控制器扩展的 controller.php 实现。该validate()方法调用:

$validator = $this->getValidationFactory()
             ->make($request->all(), $rules, $messages, $customAttributes);

So it ends up using the make()method eventually. There is a difference in how it is handled, since $this->validatecalls:

所以它最终使用了这个make()方法。它的处理方式有所不同,因为$this->validate调用:

if ($validator->fails()) {
    this->throwValidationException($request, $validator);
}

So using Validator::make()will allow you to handle the exception yourself, instead of $this->validate()auto throwing the validation exception for you. This is useful for doing something beforeyour redirect. You show this in your first example, since you check if the validation fails before deciding how to handle it. In the second example you know that if validation fails it will automatically refuse the request.

因此 usingValidator::make()将允许您自己处理异常,而不是$this->validate()自动为您抛出验证异常。这对于重定向之前做一些事情很有用。您在第一个示例中展示了这一点,因为您在决定如何处理之前检查验证是否失败。在第二个示例中,您知道如果验证失败,它将自动拒绝请求。

回答by kenken9999

if fail any rules on $this->validate, will auto throw an error

如果任何规则失败$this->validate,将自动抛出错误

$validator::make:you can easy handle the errors and may be you want wrap any data to array() and pass to $validator::make:for Validation

$validator::make:您可以轻松处理错误,并且可能希望将任何数据包装到 array() 并传递给$validator::make:验证

and also if you want to use FormRequest + Route Model Binding

并且如果您想使用 FormRequest + Route Model Binding

your store() look like this

你的商店()看起来像这样

public function store(YourFormRequestRules $request)
    {
        Helpers::storeServer($request);

        return redirect('dashboard')->with('success', 'Server stored');
    }

public function update(YourFormRequestRules $request, Post $post)
{
    $post->title = $request->input('title');
    $post->save();
    return redirect()->route('example.index');
}

thats all

就这样

回答by Oluwatobi Samuel Omisakin

Using $this->validate(): YourControllerextends a Controllerclass which uses ValidatesRequeststrait and it looks like this:

Using $this->validate(): YourControllerextends 一个Controller使用ValidatesRequeststrait的类,它看起来像这样:

namespace App\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController
{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

The ValidatesRequeststrait itself is made up of several methods that the base Controller gets and then your own controller and which includes:

ValidatesRequests特性本身是由几种方法基本得到控制,然后你自己的控制器,其中包括了:

validateWith($validator, Request $request = null)
...
validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
...
validateWithBag($errorBag, Request $request, array $rules, array $messages = [], array $customAttributes = [])
... and so on...

These methods helps makes some validation and request errors handling much convenient and in fact considering the mentioned validate()method.

这些方法有助于使一些验证和请求错误处理变得非常方便,实际上考虑到了提到的validate()方法。

When there's validation error in the request passed, it helps you handle the response without litering your controller with unneeded logic; i.e when it's an ajax call it returns a 422 response with a json body while it returns populates the error bag and fill the $errorsvariable for use in the blade template for non-ajax.

当传递的请求中存在验证错误时,它可以帮助您处理响应,而无需使用不需要的逻辑来修改控制器;即,当它是一个 ajax 调用时,它返回一个带有 json 主体的 422 响应,同时它返回填充错误包并填充$errors用于非 ajax 的刀片模板中的变量。

In summary, this only helps you incase you don't want to do manual validation by creating an instance of Validator, so to keep the developer focus on doing the real work ;)

总而言之,这只会帮助您防止您不想通过创建 Validator 实例来进行手动验证,以便让开发人员专注于做真正的工作;)

UPDATE:

更新:

$validator = Validator::make() //creates an instance of the validator for further operations

// You can even do after the creating the instance of validator:
$this->validateWith($validator, $request)

//Lets do both steps above i.e the validation and trigger the Validation Exception if there's failure.
$this->validate($request, [...rules...], [...messages..]) 

Check: https://laravel.com/docs/5.6/validation#quick-writing-the-validation-logic

检查:https: //laravel.com/docs/5.6/validation#quick-writing-the-validation-logic

回答by Elbo S.P.

Validator helper makes me more happy

验证器帮手让我更开心

$validator = validator()->make(request()->all(), [
    'type' => 'required|integer'
]);

if ($validator->fails())
{
    redirect()->back()->with('error', ['your message here']);
}

Laravel give helper that makes developing more convince.

Laravel 提供了使开发更有说服力的助手。