需要修复if语句Laravel

时间:2016-07-09 15:59:16

标签: php 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();
    }
}

通过这个查询我可以多次喜欢同一篇文章。有人可以建议一些代码吗?

2 个答案:

答案 0 :(得分: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 :(得分: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();
}