How to implement toggleLike() method in Overtrue\LaravelLike laravel package

You can implement toggleLike() method in the Overtrue\LaravelLike laravel package. You can simply use toggleLike() method on the post which you want to like if it is not already like by logged in user and remove it from like if it is already liked by the user.

Answers 2
  • Add like and remove like from post using toggle method in Overtrue\LaravelLike laravel package

    public function likePost(Request $request){
        $post = Post::find($request->id);
        $response = auth()->user()->toggleLike($post);
        return response()->json(['success'=>$response]);
    }
    
    0

    This toggleLike() method is used in Overtrue\LaravelLike laravel package to add like if the post is not liked by the logged-in user and remove like from the post if the user already liked the post.

  • Increment/decrement like counter in view file on ajax using Overtrue\LaravelLike package in laravel

    //Like counter
    <i  class="fas fa-thumbs-up {{ auth()->user()->hasLiked($post) ? 'like-post' : '' }}"></i> <div id="like{{$post->id}}-bs3"> {{ $post->likers()->get()->count() }} </div>
    
    //Like anchor tag 
    <a href="javascript:void(0)" class="like-post-btn" data-id="{{ $post->id }}">
        <i class="fas fa-thumbs-up {{ auth()->user()->hasLiked($post) ? 'liked-post' : '' }}"></i>Like
    </a>
    //Call ajax on click like button (use jQuery)
    <script>
    $('.like-post-btn').click(function(){    
        var id = $(this).data('id');
        var c = $('#like'+id+'-bs3').html();
        var cObjId = id;
        var cObj = $(this);
        
        $.ajax({
            type:'POST',
            url:'/like-post',
            data:{id:id},
            success:function(data){
                if($.isEmptyObject(data.success)){
                    $('#like'+cObjId+'-bs3').html(parseInt(c)-1);
                    $(cObj).find('.fas.fa-thumbs-up').removeClass("liked-post");
                }else{
                    $('#like'+cObjId+'-bs3').html(parseInt(c)+1);
                    $(cObj).find('.fas.fa-thumbs-up').addClass("liked-post");
                }
            }
        });
    });
    </script>
    
    0

    You can display like counter in view file using jquery method after call ajax on click like button.

  • Back to code snippet queries related laravel