Comments System Implementation for Website

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1212
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_bitrix-bitrix-24-1c_fixper_448_0.png
    Website development for FIXPER company
    815

Comments System Implementation

A comments system allows users to discuss materials. Key decisions: custom implementation vs ready-made widget (Disqus, Commento), nesting (flat vs nested), moderation.

Database Structure

CREATE TABLE comments (
    id          SERIAL PRIMARY KEY,
    entity_type VARCHAR(50)  NOT NULL,  -- 'article', 'product', 'post'
    entity_id   INTEGER      NOT NULL,
    parent_id   INTEGER REFERENCES comments(id) ON DELETE SET NULL,
    user_id     INTEGER REFERENCES users(id),
    author_name VARCHAR(100),           -- for guests
    author_email VARCHAR(255),
    body        TEXT         NOT NULL,
    status      VARCHAR(20)  NOT NULL DEFAULT 'pending',  -- pending|approved|rejected|spam
    likes_count INTEGER      NOT NULL DEFAULT 0,
    created_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ  NOT NULL DEFAULT NOW()
);

CREATE INDEX ON comments(entity_type, entity_id, status, created_at);
CREATE INDEX ON comments(parent_id);
CREATE INDEX ON comments(user_id);

Laravel API

class CommentController extends Controller
{
    // Get comments to material
    public function index(Request $request, string $entityType, int $entityId): JsonResponse
    {
        $comments = Comment::where('entity_type', $entityType)
            ->where('entity_id', $entityId)
            ->where('status', 'approved')
            ->whereNull('parent_id')  // only root
            ->with(['user:id,name,avatar', 'replies' => fn($q) => $q->where('status', 'approved')->with('user:id,name,avatar')])
            ->latest()
            ->paginate(20);

        return response()->json($comments);
    }

    // Add comment
    public function store(StoreCommentRequest $request, string $entityType, int $entityId): JsonResponse
    {
        $this->throttle('comments', 10, 60);  // 10 comments per minute

        $requiresModeration = !auth()->check()
            || auth()->user()->comments()->where('status', 'spam')->exists()
            || $this->containsSuspiciousLinks($request->body);

        $comment = Comment::create([
            'entity_type'  => $entityType,
            'entity_id'    => $entityId,
            'parent_id'    => $request->parent_id,
            'user_id'      => auth()->id(),
            'author_name'  => auth()->user()?->name ?? $request->author_name,
            'author_email' => auth()->user()?->email ?? $request->author_email,
            'body'         => $this->sanitize($request->body),
            'status'       => $requiresModeration ? 'pending' : 'approved',
        ]);

        if ($comment->status === 'approved') {
            $this->notifyParentAuthor($comment);
        } else {
            // Notify moderators
            Notification::send(
                User::moderators()->get(),
                new CommentPendingNotification($comment)
            );
        }

        return response()->json(CommentResource::make($comment), 201);
    }

    private function sanitize(string $body): string
    {
        return strip_tags($body, '<b><i><em><strong><a><br><p>');
    }

    private function containsSuspiciousLinks(string $body): bool
    {
        preg_match_all('/<a[^>]+href=["\']?([^"\'> ]+)/i', $body, $matches);
        foreach ($matches[1] ?? [] as $url) {
            if (!str_contains($url, config('app.url'))) {
                return true;
            }
        }
        return false;
    }
}

React: Comments Tree

interface Comment {
  id: number;
  user: { name: string; avatar: string } | null;
  author_name: string;
  body: string;
  likes_count: number;
  created_at: string;
  replies?: Comment[];
}

function CommentThread({ entityType, entityId }: { entityType: string; entityId: number }) {
  const { data, isLoading } = useQuery({
    queryKey: ['comments', entityType, entityId],
    queryFn: () => api.get(`/comments/${entityType}/${entityId}`),
  });

  return (
    <section aria-label="Comments">
      <h2>Comments ({data?.meta.total ?? 0})</h2>
      <CommentForm entityType={entityType} entityId={entityId} />

      {isLoading ? <CommentSkeleton /> : (
        <ul className="comment-list">
          {data?.data.map(comment => (
            <CommentItem key={comment.id} comment={comment} depth={0} />
          ))}
        </ul>
      )}
    </section>
  );
}

function CommentItem({ comment, depth }: { comment: Comment; depth: number }) {
  const [showReplyForm, setShowReplyForm] = useState(false);

  return (
    <li className={`comment depth-${depth}`}>
      <img
        src={comment.user?.avatar || '/default-avatar.png'}
        alt={comment.user?.name || comment.author_name}
        width={40} height={40}
      />
      <div className="comment__content">
        <header>
          <strong>{comment.user?.name || comment.author_name}</strong>
          <time dateTime={comment.created_at}>
            {new Date(comment.created_at).toLocaleDateString('en-US')}
          </time>
        </header>
        <p>{comment.body}</p>
        <footer>
          <LikeButton commentId={comment.id} count={comment.likes_count} />
          {depth < 3 && (
            <button onClick={() => setShowReplyForm(!showReplyForm)}>Reply</button>
          )}
        </footer>

        {showReplyForm && (
          <CommentForm parentId={comment.id} onSubmit={() => setShowReplyForm(false)} />
        )}

        {comment.replies?.map(reply => (
          <ul key={reply.id}><CommentItem comment={reply} depth={depth + 1} /></ul>
        ))}
      </div>
    </li>
  );
}

Comment Likes

class CommentLikeController extends Controller
{
    public function toggle(Comment $comment): JsonResponse
    {
        $userId = auth()->id();
        $key    = "comment_like:{$comment->id}:{$userId}";

        if (Cache::has($key)) {
            Cache::forget($key);
            $comment->decrement('likes_count');
            return response()->json(['liked' => false, 'count' => $comment->likes_count]);
        }

        Cache::put($key, true, now()->addYears(1));
        $comment->increment('likes_count');

        return response()->json(['liked' => true, 'count' => $comment->likes_count]);
    }
}

Implementation Timeline

Comments system (flat) with moderation for Laravel + React: 3–4 days. With nesting, likes, and email notifications: 5–7 days.