serge-benard's avatar

Validation Fails on Second Unique Value Test on Update

Hello!

I've got a problem with Validation. I've googled for an answer, but the only option I saw (doesn't relate directly to my issue) requires me to create my own Validation rule, which seems like overkill?

I have a table with two columns which need to be Unique.

When creating the record, the validation works fine.

When I try to Update, the 'Abbreviation' field shows as duplicate.

public function update(Request $request, Film $film)
{
    //
    $this->validate($request, [
        'name' => 'required|min:3|unique:"films", "name", ' . $film->id ,
        'abbreviation' => 'required|max:5|unique:"films", "abbreviation", ' . $film->id,
        'type_id' => 'required|numeric|filled',
    ]);

    $film = new Film;

    $film->name = $request->name;
    $film->abbreviation = $request->abbreviation;
    $film->type_id = $request->type_id;

    $film->save();

    return redirect()->route( 'films.index' )->with('message', 'Successfully updated Film.');
}

What's happening? What am I doing wrong?

Thank you!

Serge

0 likes
4 replies
serge-benard's avatar

I still can't find a resolution to this problem.

Can anyone help?

Cronix's avatar

If you are updating, why are you creating a new one? I'm assuming the $film you are passing into the method is the one that needs updating? Try just removing the: $film = new Film;

$film should be the current Film record you are updating.

1 like
Cronix's avatar
Cronix
Best Answer
Level 67

also, I think your unique rule is a bit off. It should all be in a single string instead of multiple strings. Something like '...unique:films,abbreviation,'.$film->id,

1 like
serge-benard's avatar

@Cronix you keep giving me great advice!

It just so happens I spent an hour or so refactoring the code, tweaking and trying a few things, and did exactly the two things you suggested, and it works!

I'll mark your answer as the answer to my issue.

Thanks so much again!!!

Please or to participate in this conversation.