2016-03-21 38 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