【问题标题】:Ignore unique validation while update data更新数据时忽略唯一验证
【发布时间】:2018-10-26 00:46:35
【问题描述】:

在我的产品表中product_name 是独一无二的。如果我在更新数据时不更新产品名称,它不会让我更新我的产品信息并显示以下错误:

产品名称已被占用

如何在更新同一产品时忽略唯一名称?
这是我用于更新的代码:

public function update(Request $request, $id)
  {
     $product = Product::find($id);     
     $this->validate($request, [ 
         'product_name'=> 'unique:products,product_name,'.$product->id ,          
     ]);  
     $product->product_name = Input::get('product_name'); 
     $product->product_unit_price = Input::get('product_unit_price');
     $product->save();         
     return Redirect::to('products');
  }

【问题讨论】:

  • 您确定您设置的名称实际上并未被数据库中的另一行占用吗?你在做什么应该根据docs工作。另外,请确保您得到正确的$id。
  • 规则似乎没问题,您确定您获得的是$id 并且产品具有相同的 id?
  • 我觉得应该是'product_name'=> 'unique:products,product_name,'.$product->id.',id'
  • $id 是正确的。查了好几遍

标签: php laravel laravel-5


【解决方案1】:

确保您已使用 use Illuminate\Http\Request...并带有正确的表字段名称和输入名称。

$request->validate([
    'product_name' => 'required|unique:products,product_name,'.$product->id,
]);

【讨论】:

    【解决方案2】:

    如果您只使用unique 验证规则,那么您可以使用:

    $this->validate($request, [
                'product_name' => Rule::unique('products')->ignore($product->id),
                  ]);
    

    或者如果您也有其他验证规则,请使用这种方式:

    $this->validate($request, [
        'product_name' => [
                    'required',
                    Rule::unique('products')->ignore($product->id),
                 ],
         ]);
    

    但在使用之前包含use Illuminate\Validation\Rule;。

    【讨论】:

    • 我使用了您的两种解决方案,但我收到的消息相同 product name has already been taken
    • 数据库中有product_name列吗?
    • 是的..名字没问题
    猜你喜欢
    • 2017-10-05
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 1970-01-01
    • 2013-06-03
    • 1970-01-01
    • 2021-02-07
    • 2019-01-10
    相关资源
    最近更新 更多