Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ignoring the user result input when updating data goes wrong

I’m working on an edit.blade.php where users can edit data and the update method of Controller goes here:

public function update(Request $request, $id)
    {
        $discountCode = DiscountCode::find($id);

        $request->validate([
            'code' => 'unique:discount_codes,code'.$discountCode->id,
            'started_at' => 'required_if:timespan,TRUE',
            'ended_at' => 'required_if:timespan,TRUE',
        ],
  
        ...
    }

So as you can see the code must be uique in discount_codes table.

So I tried adding $discountCode->id in order to ignore unique validation rule for the current data but it does not work out and returns this error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SQLSTATE[42S22]: Column not found: 1054 Unknown column ‘code15’ in ‘where clause’ (SQL: select count(*) as aggregate from discount_codes where code15 = GIGvJjp4PM)

15 is my data row id.

So what’s going wrong here? How can I solve this issue?

>Solution :

Use Rule::class to create the rule and ignore specific id

use Illuminate\Validation\Rule;

//...

public function update(Request $request, $id)
{
    $discountCode = DiscountCode::findOrFail($id);

    $request->validate([
        'code' => [Rule::unique('discount_codes')->ignore($id)],
        'started_at' => 'required_if:timespan,TRUE',
        'ended_at' => 'required_if:timespan,TRUE',
    ],

    ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading