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

webfuelcode @webfuelcode

About: Like to learn something new. Coding is fun.

Joined:
Jul 21, 2020

Laravel Check, In Controller If The User Has Liked It

Publish Date: Mar 13 '21
6 0

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

Comments 0 total

    Add comment