【问题标题】:Laravel 5.6 $this->validate vs Validator::make()Laravel 5.6 $this->validate 与 Validator::make()
【发布时间】:2018-12-14 02:41:17
【问题描述】:

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

这些都有适当的用途吗?比如什么时候使用一个与另一个?

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

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

$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->验证:

 public function store(Request $request)
    {

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

        Helpers::storeServer($request);

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

【问题讨论】:

  • 还有我最喜欢的Form Request Validation
  • @RonvanderHeijden 哇,我没有偶然发现这个页面。我一定会读一遍!

标签: php laravel validation


【解决方案1】:

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

validate() 方法调用:

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

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

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

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

【讨论】:

  • 感谢您的回复,这就是我的想法,我只是想知道社区的想法。几个月前,我在实习的时候刚接触到 laravel 框架,甚至是 php,我很喜欢它,所以我试图深入到框架的根源并尽可能多地学习!
  • 听起来不错。我会尝试浏览一些源文件并从中学习。通过查看一些基本文件,如 Controller.php、Model.php 等,您可以获得很多信息。有时,当我工作无聊时,我最终会经历那个兔子洞并最终学到一些有用的东西。
【解决方案2】:

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

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

如果你想使用 FormRequest + 路由模型绑定

你的 store() 看起来像这样

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');
}

就是这样

【讨论】:

  • 那么在将请求传递给控制器​​之前,它会被“扫描”是否有错误?
  • FormRequest 允许您可以重用规则,大多数用于存储/更新,路由模型绑定如果找不到 id 将抛出 404,如您所见,我没有使用 find(id)关于我的更新方法
  • 我一定会为此查看 larvael 文档,看看如何在应用程序中使用它!非常感谢您的回复!
【解决方案3】:

使用$this->validate()YourController 扩展了一个使用ValidatesRequests 特征的Controller 类,它看起来像这样:

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;
}

ValidatesRequests trait 本身由基本 Controller 获取的几个方法组成,然后是您自己的控制器,其中包括:

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

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

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

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

更新:

$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..]) 

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

【讨论】:

    【解决方案4】:

    验证器助手让我更开心

    $validator = validator()->make(request()->all(), [
        'type' => 'required|integer'
    ]);
    
    if ($validator->fails())
    {
        redirect()->back()->with('error', ['your message here']);
    }
    

    Laravel 提供帮助,让开发更有说服力。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-31
      • 2023-01-01
      • 2018-12-31
      • 2018-12-10
      相关资源
      最近更新 更多