2016-03-21 36 views
0

在我目前的系统中,用户可以为产品撰写评论。防止用户对产品提交多个评论

下面是其中的审查验证,并创造发生在我的控制器的方法:

public function PostAndValidate($id) 
{ 
    $input = [ 
     'comment' => Input::get('comment'), 
     'rating' => Input::get('rating') 
    ]; 
    $review = new Review; 
    $validator = Validator::make($input, $review->getCreateRules()); 
    return to product page with error message 
    if ($validator->passes()) { 
     $review->storeReviewForBook($id, $input['comment'], $input['rating']); 
     return Redirect::to('book/'.$id.'#reviews-anchor')->with('review_posted',true); 
    } 

    return Redirect::to('book/'.$id.'#reviews-anchor')->withErrors($validator)->withInput(); 
} 

如何防止用户张贴一本书或产品新的评论,他(或她)已经审查?

+0

可以显示审查,书籍和用户的数据库结构吗? – Gokigooooks

+0

数据库结构up – fido

回答

2

你可以在你的storeReviewForBook方法如下:

$book = Book::find($id); 

if(in_array(Auth::user()->id, $book->reviews->lists('user_id')->all())) { 
    return redirect()->back()->with('message', 'You already reviewed this book'); 
} 
+0

我不认为你需要 - >所有()列表后。 – Gokigooooks

+0

它在5.1中引入。除非它在5.2中恢复。似乎没有在文档中。 – user2094178

+0

我也不认为这会起作用,因为storeReviewForBook在模型中,并且从该范围返回将不会影响在控制器中运行的脚本。他应该在控制器中进行验证。 – Gokigooooks

1

首先作为一个良好的习惯,尽可能把所有的逻辑控制器。您在Review模型文件中不需要storeReviewForBook。

我会写你的postAndValidate功能像这样,

public function PostAndValidate($id) 
{ 
    $input = [ 
     'comment' => Input::get('comment'), 
     'rating' => Input::get('rating') 
    ]; 

    $review = new Review; 
    $validator = Validator::make($input, $review->getCreateRules()); 

    if ($validator->passes()) { 

     //queries for a review with book id and user id matching the current transaction 
     $existing = Review::where('book_id','=',$id) 
         ->where('user_id','=',Auth::user()->id) 
         ->first(); 
     //last query returns null if nothing is returned 
     if($existing!=null) 
     { 
      return redirect()->back()->with('message', 'You already reviewed this book'); 
     } 
     else 
     { 

      $review->comment = $input['comment']; 
      $review->rating = $input['rating']; 
      $review->book_id = $id; 
      $review->user_id = Auth::user()->id; 
      $review->save(); 

      return Redirect::to('book/'.$id.'#reviews-anchor')->with('review_posted',true); 
     } 


    return Redirect::to('book/'.$id.'#reviews-anchor')->withErrors($validator)->withInput(); 
} 

模型应该是与数据库交互层,而你把你的逻辑控制器。它也更可读,更易于调试。

编辑 作为数据完整性的一种形式,您可以在user_id和book_id中添加一个唯一的索引在评论表中。将user_id和book_id作为数组放在一起,这样唯一的索引将被合并为2列。

//in migration file 
$table->unique(['user_id','book_id']); 
+0

我得到这个错误in_array()期望参数2是数组,对象给出 – fido

+0

@fido添加更改 – Gokigooooks

+0

我得到这个错误 - 试图获得非对象的属性 – fido