Ignore unique validation while update data

In my products table product_name is unique. If i don't update the product name while updating the data, it won't let me update my product information and shows the following error:

product name has already been taken

How can I ignore the unique name while updating same product?
Here is the code i have used for updating:

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

2 answers

  • answered 2018-05-16 05:36 Muhammad Nauman

    if you are using just the unique validation rule then you can use:

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

    Or if you have other validation rules too then use this way:

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

    But include use Illuminate\Validation\Rule; before using it.

  • answered 2018-05-16 05:39 dekts

    make sure you have use use Illuminate\Http\Request...with correct table field name and input name.

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