Laravel针对唯一值的验证

时间:2018-12-09 16:25:14

标签: laravel validation laravel-5

我想为更新功能创建一个验证 我希望它排除该行ID的标题

  public function update(Request $request, Post $post)
    {
      $this->validate($request,[
         'title' => "required|unique:posts,title,".$id.'id',
         'image' => 'image',
         'categories' => 'required',
         //'tags' => 'required',
         'body' => 'required',
     ]);

3 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

 public function update(Request $request, $id)
 {
    $rules = [
              'title' => 'required|unique:posts,title,'.$id,
              'image' => 'image',
              'categories' => 'required',
              'body' => 'required',
            ];
    $this->ValidateForm($request->all(), $rules);
    $post= Post::find($id);  
    if($post){
       $post->title  = $request->title;
       $post->categories  = $request->categories;
       $post->body  = $request->body;
       if ($request->hasFile('image')){
             Storage::delete($request->profile_photo);
             $post->image = $request->file('image')->store('post');
       }
      $post->save();
    }
 }

答案 1 :(得分:0)

此代码将起作用,

 public function update(Request $request, Post $post)
        {
          $this->validate($request,[
             'title' => ["required,unique:posts,title,".$this->route('post')],
             'image' => 'image',
             'categories' => 'required',
             //'tags' => 'required',
             'body' => 'required',
         ]);

让我知道它对您有用。

答案 2 :(得分:0)

我提出了另一个可行的示例,也许可以派上用场

    public function update(Request $request, $id)
    {
      $this->validate($request,[
  'name' => "required|unique:categories,name,".$id.'id',
  'image' => 'mimes:jpeg,bmp,png,jpg'
]);