2016-07-09 62 views
-1

我需要確保當用戶「喜歡」發佈它不能再被一個用戶喜歡一次。這是我目前想要做的:需要修復,如果語句Laravel

public function liked($id) 
{ 
    $like = new Like(); 
    $post = Post::where('id', $id)->first(); 
    if($post->user_id != Auth::user()->id && $like->user_id != Auth::user()->id) { 
     $like->user_id = Auth::user()->id; 
     $like->post_id = $post->id; 
     $like->like = 1; 
     $like->save(); 
     return redirect()->back(); 
    } else { 
     return redirect()->back(); 
    } 
} 

使用此查詢,我可以多次訪問同一帖子。有人可以建議一些代碼?

回答

1

花點時間閱讀Laravel的關係,他們在這種情況下確實很有幫助。

public function liked($id) 
{ 
    $uid = Auth::user()->id; 
    $likes = Like::where('post_id', $id) 
       ->where('user_id', $uid)->get(); 

    if ($likes->count() == 0) 
    { 
     $like = new Like; 
     $like->user_id = $uid; 
     $like->post_id = $id; 
     $like->like = 1; 
     $like->save(); 
    } 
    return redirect()->back(); 
} 

注意此代碼假定$id傳遞是一個有效的崗位。

1
public function liked($id) 
{ 
    // find the post 
    $post = Post::find($id); 

    // the logged in user 
    $user = Auth::user(); 

    // user not allowed to like their own post 
    if ($post->user_id == $user->id) { 
     return redirect()->back(); 
    } 

    // search each like for the post 
    // if the user created the like, exit and redirect back 
    // (relationship must be defined in the models)   
    foreach ($post->likes as $like) { 
     if ($like->user_id == $user->id) { 
      return redirect()->back(); 
     } 
    } 

    // create and save the link 
    $like = Like::create([ 
     'user_id' => $user->id, 
     'post_id' => $post->id 
    ]); 

    return redirect()->back(); 
}