labas GamePage visogero labas GamePage visogero - 4 months ago 10
PHP Question

Need to fix if statement Laravel

I need to make sure that when user "likes" post it cannot be liked one more time by the same user. This is what I'm trying to do currently:

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();
}
}


With this query I can like multiple times the same post. Can someone suggest some code ?

geo geo
Answer

Take some time and read up on Laravel relations, they are really helpful in situations like this.

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();
}

Note this code assumes the $id passed in is to a valid post.