DEV Community

webfuelcode
webfuelcode

Posted on • Updated on

Laravel Check, In Controller If The User Has Liked It

Laravel function to check if the user has already added(liked, followed...) the post.

If he did, then remove otherwise add it.

Here suppose post like and it is a pivot table. First, you check if the user has already liked the post and then the action will depend on it. If they liked, the same link will remove it otherwise it will add it to the database.
Check If The User Has Liked The Post In Laravel Controller

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

Top comments (0)