2

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

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

tysm. ignore by id didnt work, this works perfectly.
1

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

1 Comment

It seems like I had duplicate titles in the database. I don't know why but I deleted all the duplicates in the database and now it works. Rule::unique('articles')->ignore($article->id) and Rule::unique('articles')->ignore($article) and Rule::unique('articles', 'title')->ignore($article->id) are all working now.
1

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

Comments

0

If you use softDelete and you deleted an object that has the same title, don't forget to check if the deleted_at column is null.

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

Comments

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.