Laravel unique validation rule with except not working

Viewed 1585

Laravel unique validation rule with except column not working on update, what's wrong in my code ?

public function update(Request $request, Article $article)
{
    abort_if($article->user_id !== $request->user()->id, 403);

    $article = $request->user()->articles()->update($request->validate([
        'title' => [
            'required',
            Rule::unique('articles', 'title')->ignore($article->id)
        ],
        'content'=>'required|min:90',
    ]));

    return redirect('articles/'.$article->id)->withSuccess('Article saved.');
}

Error : The title has already been taken.

Laravel version : 6.4.0

Thanks for help

3 Answers

You can pass the entire instance of article to validate like:

Rule::unique('articles')->ignore($article);

Because you are already saying what column to check.

https://laravel.com/docs/6.x/validation

Remove title from

Rule::unique('articles', 'title')->ignore($article->id)

to

...
$article = $request->user()->articles()->update($request->validate([
        'title' => [
            'required',
            Rule::unique('articles')->ignore($article->id)
        ],
        'content'=>'required|min:90',
    ]));
...

Hope this helps

more info, check rule-unique

If you run the update on $request->user()->articles() you will update all of the user's articles. If the user only has 1 article then it should work just fine, however if there are more then this will result in data being overwritten.

Instead do:

$article->update($request->validate([
    'title' => [
        'required',
        Rule::unique('articles', 'title')->ignore($article->id)
     ],
    'content'=>'required|min:90',
]));
Related