DEV Community

loading...

Laravel Check, In Controller If The User Has Liked It

webfuelcode
Like to learn something new. Coding is fun.
Updated on ・1 min read

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.

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

Discussion (0)