DEV Community

webfuelcode
webfuelcode

Posted on • Edited on

2 3

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

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs