Show likes and dislikes of comments in API

  api, laravel

I have an API for show posts, likes and dislikes, and comments with likes.

The relation between post and comments is polymorphic one to many

likes is a column in comments table and i change type of it to ‍‍array in Comment model in casts part

the problem is than i don’t know exactly how to write the code correctly about showing comment likes

so for add like, i wrote this :

CommentLikeController :

public function addLike($id)
        $comment = Comment::find($id);

        $likes = $comment->likes;

        $user_id = JWTAuth::user()->id; // for add user ID to likes array

            if (!in_array($user_id, $likes)) { //check user id is in likes array or not

                array_push($likes, $user_id); // add new user id to likes

                $comment->likes = $likes;

                $message = "liked";
            } else {
                $message = "liked before";

        return response()->json($message);

for example i have the a comment with likes :

likes = [1,2,6,8,11,99,34,89]

To get the number of likes of this comment , i use count() :

$likesCount = count($comment->likes)

so my problem is i don’t know how to handle and use this foreach when i want to show post and post likes , comments and replies with likes in this controller

public function showPost($id){

        $postFind = Post::find($id);
            return response()->json('not found' , 404);

        $post = Post::find($id);

        //Number of likes of the post
        $postLikes = $post->likes;
        $postLikesCount = count($postLikes);

        //show comments of posts
        $comments = Comment::where('commentable_type' , 'AppModelsPost')->first();

            $comments = 'there is no comment for this post yet';

            $commentsGet = Comment::where('commentable_type' , 'AppModelsPost')->with('replies.replies')->get();

            foreach  ($commentsGet as $commentGet){
                $cmLikes =$commentGet->likes;

                $commentLikes = count($cmLikes);


            $comments = Comment::where('commentable_type' , 'AppModelsPost')->with('replies.replies')->get();


        return response()->json([
           'post'  => $post,
           'post views'  => $views ,
           'post likes count' => $postLikesCount ,
           'post dislikes count' => $postDislikesCount ,

            ] , 200);


Source: Laravel

Leave a Reply