Asked Dec 26th, 2019 6:47 a.m. 2341 0 5
  • 2341 0 5
+1

Hỏi về Validation unique laravel khi update bài viết ạ

Share
  • 2341 0 5

Chào mọi người ạ, em đang gặp 1 vấn đề là khi edit 1 post, thi validation của em có check unique title trong database và khi em không thay đổi gì title vẫn để title cũ mà update là nó báo đã tồn tại. Cho em hỏi lỗi này fix ntn ạ? Em viết validation trong thư mục Request riêng ạ. Mong mọi người giúp đỡ

Avatar Hải Hà @HaiHaChan
Dec 26th, 2019 6:49 a.m.

bạn show code phần update được k ạ?

0
| Reply
Share

5 ANSWERS


Answered Dec 26th, 2019 6:49 a.m.
+5

Bạn vẫn dùng unique rule như này nhé:

'title' => "unique:posts,title,$postId,id"

Thì nó sẽ vẫn áp dụng rule unique nhưng sẽ bỏ qua bài viết có id là $postId nhé bạn

Share
Answered Dec 26th, 2019 6:51 a.m.
+3

bạn có thể dùng cách này

public function rules()
{
       $id = $this->route('post')->id; // lấy id bài post muốn update
        return [
            'title' => "unique:posts,title,{$id},id"
         ]
}
Share
Answered Dec 26th, 2019 6:54 a.m.
+2

use Illuminate\Validation\Rule;

Validator::make($data, [ 'posts' => [ 'required', Rule::unique('posts')->ignore($postId), ], ]);

Bạn thử dùng hàm ignore() xam sao chi tiết bạn có thể tham khảo: https://laravel.com/docs/6.x/validation#rule-unique

Share
Answered Dec 28th, 2019 2:14 p.m.
0

Bạn làm như này nhé:

/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
     $id = $this->route('certificate')->id;

     return [
        'title' =>"unique:potsts,title,$id,id",
     ];
}
Share
Answered Dec 26th, 2019 7:08 a.m.
-5

Cám ơn mọi người nhìu em đã làm được rồi. Thanks nhìu ạ!

Share
Viblo
Let's register a Viblo Account to get more interesting posts.