简体   繁体   中英

laravel error when i try to update unique field

when I just change the title field the content field will be an error because it only accepts unique value, if I don't use unique validation then there will be a possibility of paper with the same title, and I don't want it.

My method in controller:

 public function update(Paper $paper)
   {
       // validation
       $data = request()->validate([
           'title' => ['required', 'unique:papers'],
           'content' => ['required']
       ]);
       $data['slug'] = \Str::slug(request('title'));

       $paper->update($data);

       return redirect()->route('papers.show', $paper);
   }

Thanks for the help.

Welcome to StackOverflow!

This happens, because Laravel doesn't know what exact item you're trying to update. It simply checks if the given title exists already in the database. This is the case when you update your entity without changing it's title. Basically it is doing exactly what you asked it to do.

To prevent this, Laravel supports the option to exclude a given id from the rule. Instead of using unique:title , try using the following in your rule-set for an update. Be sure to import the Rule class:

'title' => [
    // ...
    Rule::unique('papers')->ignore($paper->id),
];

You can find more details about this procedure in the official documentation:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM