Check If The User Has Liked The Post In Laravel Controller

Laravel Check, In Controller If The User Has Liked It.

How to check using the if-else statement in Laravel controller, if the user has liked the post?

What does this function do?

The function basically checks first if the user has liked the post. Then the action is decided accordingly.

Solution

The function below is written keeping in mind that a separate Like table is created with polymorphic relation. So you have the post-id and user-id.

This function does the two actions. This means it deletes the previous entry if there is already one and adds if there is no same entry.

Code

public function saveLike(Request $request)
    {
        $likecheck = Like::where(['user_id'=>Auth::id(),'post_id'=>$request->id])->first();
        if($likecheck){
            Like::where(['user_id'=>Auth::id(),'post_id'=>$request->id])->delete();
            return 'delete';
        }
        else{
            $like = new Like;
            $like->user_id = Auth::id();
            $like->post_id = $request->id;
            $like->save();
        }
    }

First, check if the user has liked the post. If the statement is true, then delete it.

Otherwise, add a new entry. Which is new like with post-id and user-id.

Related Posts