0

I have a products table and unique column, but when I try to update it fails and show me unique error message.I try to make something to ignore, but does not work.

 $attributes = $request->validate([
            'name' => 'required|min:3',
            'description' => 'nullable|min:3',
            'selling_price' => 'required|numeric',
            'purchase_price' => 'required|numeric',
            'quantity' => 'required|integer',
            'unit' => 'nullable',
            'stock_alert' => 'nullable|numeric',
            'unique_code' => "required|unique:products,unique_code,$product->id",
            'awb' => 'required|numeric'
        ]);

Thank you so much!

1
  • 1
    Store or update method? To make an update, take the id out of the quotation marks "required|unique:products,unique_code,". $product->id. To make store method, just required|unique:products Commented Jun 24, 2019 at 12:57

2 Answers 2

2

You can ignore a field like this

use Illuminate\Validation\Rule;

 $attributes = $request->validate([
            'name' => 'required|min:3',
            'description' => 'nullable|min:3',
            'selling_price' => 'required|numeric',
            'purchase_price' => 'required|numeric',
            'quantity' => 'required|integer',
            'unit' => 'nullable',
            'stock_alert' => 'nullable|numeric',
            'unique_code' => [
                "required",
                Rule::unique('products', 'unique_cod')->ignore($product->id),
             ],
            'awb' => 'required|numeric'
        ]);
Sign up to request clarification or add additional context in comments.

7 Comments

It still fails, and show me this error message.The unique code has already been taken.
what is the primary key of products table ?
$table->bigIncrements('id');
can you make sure $product->id is the id of the record you have been updating
I used dd to display and it's the correct id.. I dont know why is not working.I am using route-model binding.
|
0

Ignoring it isn't the right way. You use a validation for some reason.

To make an update, just take the product id out of the quotation marks like this:

'unique_code' => 'required|unique:products,unique_code,'. $product->id,

3 Comments

It still fails, and show me this error message.The unique code has already been taken.
'unique_code' => 'required|unique:products,unique_code,' .$product->id,
Get the id of the product you want to update, for example 1000, change the validation to 'unique_code' => 'required|unique:products,unique_code,1000', check if it fails with that exact product, if not, you are not passing the id correctly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.