Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forcing A Unique Rule To Ignore A Given ID

In my controller i was trying to update my product, product name here is unique and here i wanted to update only price. so name will be as it but as i defined name as a unique field though i haven't changed the name it throws me unique name validation error as this name already exist. How do i ignore that validation request when i don't update the unique value?

public function update(Request $request, $id)
        {
           $this->validate($request, [              
            'name'=> 'required|unique:products,'.$id,
            ]);        
            $product= Product::find($id);
            $product->name = Input::get('name');
            $product->price = Input::get('price'); 
            $product->save();
       }
like image 533
User57 Avatar asked Feb 15 '18 08:02

User57


2 Answers

Change it to:

'name'=> 'required|unique:products,name' . $id,
like image 139
Alexey Mezenin Avatar answered Nov 11 '22 06:11

Alexey Mezenin


Add unique column name to validation rule:

'name'=> 'required|unique:products,name,'.$id,
like image 22
Sohel0415 Avatar answered Nov 11 '22 08:11

Sohel0415