Home > database >  Ignoring the user result input when updating data goes wrong
Ignoring the user result input when updating data goes wrong

Time:04-19

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:

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?

CodePudding user response:

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',
    ],

    ...
}
  • Related