【问题标题】:Laravel unique request updateLaravel 唯一请求更新
【发布时间】:2018-07-30 17:04:13
【问题描述】:

我在 laracasts 和 Stackoverflow 上阅读了一些关于此的内容。

我有一个带有验证的更新函数:

public function update(Customer $customer, StoreCustomer $request)
{
    $customer->update($request->validated());
    exit();
}

以及验证规则:

 public function rules()
{
    return [
        'code'  => 'required|unique:customers,code',
    ]
}

现在我尝试在唯一之后添加第三个参数,所以如果它存在,它将继续。我试过这样:

 public function rules(Customer $customer)
 {
    return [
        'code'  => 'required|unique:customers,code,'.$customer->code,
    ]
}

但这似乎没有任何作用。如果您在我的控制器本身中进行验证,它似乎可以工作,但这看起来更干净。有什么解决办法吗?

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    如果要忽略当前客户,则需要将$customer->code 更改为$customer->id,假设您的主键为id

    unqiue validation documentation

    忽略当前客户:

    'code' => 'required|unique:customers,code,'.$customer->id,
    

    【讨论】:

      【解决方案2】:

      您的表单请求是一个请求。它填充了来自当前请求的数据。您可以从路由中提取customer,因为它当前绑定为参数。 $this->route('customer')

      public function rules()
      {
          return [
              'code' => 'required|unique:customers,code,'. $this->route('customer')->code,
      
              // perhaps this should be ignoring by id though?
              'code' => 'required|unique:customers,code,'. $this->route('customer')->id,
          ];
      }
      

      在这里使用方法注入只能给你一个绑定,如果一个在容器中注册了那个确切的类,或者那个类的一个新实例,这里就是这种情况。该类名称与当前可能包含恰好属于该类的模型的路由参数的概念之间没有联系。

      【讨论】:

        【解决方案3】:

        看来这样做的正确方法是

        'code'  => 'required|unique:customers,code,'.$this->route('customer')->code.',code',
        

        由于 $customer 参数在 rules() 中不可用,您需要以另一种方式获取客户。

        【讨论】:

          【解决方案4】:

          我认为最好的方法是使用 Rule:unique

          return [
              'code'  => ['required', Rule::unique('customers', 'code')->whereNot('code', $customer->code)]
          ]
          

          【讨论】:

            猜你喜欢
            • 2018-12-25
            • 2019-11-11
            • 2023-04-03
            • 1970-01-01
            • 2023-03-27
            • 2020-07-07
            • 2018-07-05
            • 2018-03-08
            • 1970-01-01
            相关资源
            最近更新 更多