【问题标题】:Laravel 5.7. Route model binding validation拉拉维尔 5.7。路由模型绑定验证
【发布时间】:2019-09-09 22:15:21
【问题描述】:

我想使用甜蜜的 Laravel 模型绑定,然后对模型本身运行一些复杂的验证检查。

类似

Route::post('/do-something/{something}', 'SomeController@store');

$request->validate([
    'something' => [
        new MyFirstVeryComplexRule,
        new MySecondVeryComplexRule,
        new MyThirdVeryComplexRule,
        //...
    ],
]);

我假设,传递给每个规则的$value 将是App\Something 类的一个实例。

有可能实现吗?

我能想到的最接近的选择是传递模型的id,然后在每个规则实例中运行App\Some::find($value),但这会降低性能并且不可扩展。

回答

不,这是不可能的,因为 x,y,z,试试 a,b,c

也将被接受。

【问题讨论】:

    标签: php laravel laravel-5 eloquent laravel-validation


    【解决方案1】:

    您可以像这样在 RouteServiceProvider 中创建自定义绑定:

    public function boot()
    {
        parent::boot();
    
        Route::bind('something', function ($value) {
            $instance = Model::find($value) ?? abort(404);
    
            $validator = Validator::make([
                'something' => $instance,
            ], [
                'something' => [
                    new MyFirstVeryComplexRule,
                    new MySecondVeryComplexRule,
                    new MyThirdVeryComplexRule
                ]
            ]);
    
            if ($validator->errors()->any()) {
                // perform on error tasks
            }
    
            return $instance;
        });
    }
    

    那么每个规则的$value 都会收到你的模型实例。

    更多信息,您可以查看Route Model Binding下的Customizing The Resolution Logichttps://laravel.com/docs/5.8/routing#route-model-binding

    【讨论】:

      【解决方案2】:

      来自Laravel's Routing documentation

      或者,您可以覆盖 Eloquent 模型上的 resolveRouteBinding 方法。此方法将接收 URI 段的值,并应返回应注入路由的类的实例:

      class YourModel {
          public function resolveRouteBinding($value, $field = null)
          {
              return $this->where('name', $value)->firstOrFail();
          }
      }
      

      您可以像 @Chin Leung 一样使用它:

      class YourModel {
          public function resolveRouteBinding($value, $field = null)
          {
              $instance = Model::find($value) ?? abort(404);
      
              $validator = Validator::make([
                  'something' => $instance,
              ], [
                  'something' => [
                      new MyFirstVeryComplexRule,
                      new MySecondVeryComplexRule,
                      new MyThirdVeryComplexRule
                  ]
              ]);
      
              if ($validator->errors()->any()) {
                  // perform on error tasks
              }
      
              return $instance;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2019-01-01
        • 2017-03-16
        • 2020-05-11
        • 1970-01-01
        • 2021-05-24
        • 2019-03-08
        • 2019-05-26
        • 2018-08-19
        • 2018-05-29
        相关资源
        最近更新 更多