【问题标题】:How to validate a Patch/Put request in Laravel如何在 Laravel 中验证 Patch/Put 请求
【发布时间】:2016-03-28 20:17:29
【问题描述】:

如何在 Laravel 中验证 Patch/Put 请求

根据 Laravel 文档 http://laravel.com/docs/5.1/controllersput/patch 请求由资源控制器的 update 操作处理

Verb         Path           Action  Route Name
PUT/PATCH   /photo/{photo}  update  photo.update

由于patch 请求应该更新部分资源而put 请求更新整个资源,那么我的FormRequest 验证rules 应该如何:

我应该这样做吗:

public function rules()
{

    $rules = [];

    if($this->has('name')) $rules['name'] = 'required';
    if($this->has('email')) $rules['email'] = 'required|email';

    return $rules;
}

依靠您的专业答案。

【问题讨论】:

  • 为什么不使用验证器中的sometimes 方法。是specifically made for these sort of things
  • 谢谢@Andrew 我知道sometimes 但你不能在FormRequest 中使用sometimes 我更喜欢使用
  • @Digitlimit 只需在 FormRequest 类中覆盖默认的 getValidatorInstance 即可

标签: laravel laravel-5


【解决方案1】:

尝试覆盖 FormRequest 类的默认 getValidatorInstance 方法

我没有尝试过,但我认为它应该可以工作 :) 希望主旨清楚

 protected function getValidatorInstance()
    { 
        $validator =  \Validator::make($this->all(), $this->rules(),  $this->messages(), $this->attributes());
        $validator->sometimes('reason', 'required|max:500', function($input) {
           return $input->games >= 100;
        });

        return $validator;
    }

【讨论】:

    猜你喜欢
    • 2016-10-24
    • 2017-04-09
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多