laravel-comments 0.3.0

Comments for Laravel Rust models: threaded replies, moderation, reactions, and events, without N+1 queries.
Documentation

laravel-comments

Crates.io Docs.rs CI License: MIT OR Apache-2.0

Comments for Laravel Rust models: blog posts, products, tasks, anything your application has. Replies nest to any depth, moderation keeps spam out, reactions count themselves, and a page of threads with authors, reactions, and the viewer's own reactions is read in seven queries, however many comments it holds.

The package is the backend only: models, migrations, an API for your code, and events. You draw the comments with whatever your application uses: a MiniJinja template, Inertia and React, or htmx.

Features

  • Comments on any model your application lists, checked at compile time
  • Authors are your users, or guests with a name and an email address that never reaches JSON
  • Threads of replies on laravel-nestedset: a whole thread in one query, a depth limit like Reddit's, sorting by oldest, newest, or best
  • Moderation: pending, approved, spam, and rejected, with automatic approval by a setting or a rule of your own, such as a spam check
  • Removing a comment never breaks a thread: a comment with replies leaves a placeholder
  • Editing with an edited_at mark, and the text before each edit kept
  • Likes and any reactions you allow: one of each per user, even under concurrent requests, counted in columns rather than with COUNT on every page
  • The viewer's own reactions for a whole page in one query
  • Links to any comment: the page it's on, for notifications
  • Comment counts on your models through with_count, without N+1 queries
  • @name mentions, announced once per user when the comment is visible
  • A default policy: authors edit and remove their own, within an edit window; moderators do everything
  • A rate limit for posting, per user or per guest's IP address
  • Markdown rendered as safe HTML, behind the markdown feature
  • Events for every change, for notifications, search indexes, or live updates, and broadcasting on a channel per commented model
  • Ready to serialize: a page of threads is one Serialize value for JSON or a template
  • Tested on SQLite, PostgreSQL, and MySQL, including concurrent likes and replies, and query counts

Installation

[dependencies]
laravel-comments = "0.3"

The package uses the database driver your application enables on laravel-rust: SQLite, PostgreSQL, MySQL, or MariaDB. It needs Rust 1.99 or later, like Laravel Rust itself.

On MySQL and MariaDB, enable the mysql feature:

[dependencies]
laravel-comments = { version = "0.3", features = ["mysql"] }

It makes replies lock their thread with a named lock. Without it, InnoDB's gap locks make concurrent writes to neighbouring threads deadlock; the package then retries them, but under load they keep waiting on each other.

Register the service provider in src/app.rs:

use laravel::Application;

Application::configure()
    .with_providers(|providers| {
        providers.add(laravel_comments::CommentsServiceProvider::new());
    })

The provider adds the package's migrations, which create comments, comment_reactions, comment_reaction_counts, comment_mentions, and comment_revisions:

laravel migrate

Quick start: comments on blog posts

Your users write the comments, so tell the package their key with Commenter:

// src/models/user.rs
use laravel_comments::Commenter;

impl Commenter for User {
    fn commenter_id(&self) -> i64 {
        self.id
    }
}

List the models people may comment on in a #[morph] enum, and declare the comment model with comment_model!. It writes a regular Laravel Rust model for the comments table:

// src/models/comment.rs
use laravel::model::morph;

use crate::models::{Post, User};

#[morph]
pub enum Commentable {
    Post(Post),
}

laravel_comments::comment_model! {
    pub struct Comment {
        commentable: Commentable,
        author: User,
    }
}

Give Post its comments. The filter counts only the comments everyone may see:

// src/models/post.rs
use laravel::model::{MorphMany, model};
use laravel_comments::CommentModel;

use crate::models::Comment;

#[model]
pub struct Post {
    pub id: i64,
    pub title: String,
    #[morph_many(Comment::commentable, filter = Comment::where_visible())]
    pub comments: MorphMany<Comment>,
}

Now post, reply, and read:

use laravel::auth::Auth;
use laravel::prelude::*;
use laravel_comments::{Author, CommentModel, Sort, ThreadPage};

use crate::models::{Comment, Post, User};

#[laravel::input]
pub struct NewComment {
    #[validate(required, max_length(10000))]
    pub body: String,
}

/// `POST /posts/{post}/comments`
pub async fn store(
    post: Post,
    Authenticated(user): Authenticated<User>,
    Valid(input): Valid<NewComment>,
) -> laravel::Result<Json<Comment>> {
    Ok(Json(Comment::post(post, Author::user(&user), &input.body).await?))
}

/// `POST /comments/{comment}/replies`
pub async fn reply(
    mut comment: Comment,
    Authenticated(user): Authenticated<User>,
    Valid(input): Valid<NewComment>,
) -> laravel::Result<Json<Comment>> {
    Ok(Json(comment.reply(Author::user(&user), &input.body).await?))
}

/// `GET /posts/{post}/comments`, for guests and signed-in users
pub async fn index(post: Post, auth: Auth<User>) -> laravel::Result<Json<ThreadPage<Comment>>> {
    let mut threads = Comment::threads(post).sort(Sort::Best).depth(4);
    if let Some(user) = auth.user().await? {
        threads = threads.viewer(&user);
    }
    Ok(Json(threads.get().await?))
}

CommentModel holds the package's API, so import it wherever you use comments.

Posting and replying

Comment::post starts a thread on any model of your enum. A model outside the enum doesn't compile: the trait bound Commentable: From<Invoice> is not satisfied.

let comment = Comment::post(post, Author::user(&user), "Great post!").await?;
let from_guest = Comment::post(post, Author::guest("Ann", "ann@example.com"), "Hi!").await?;

A reply goes under any approved comment, and reloads the comment it answers:

let reply = comment.reply(Author::user(&user), "Thanks!").await?;

Replies nest down to COMMENTS_MAX_DEPTH (8 by default), where top-level comments are depth 0. A reply to a comment at the deepest level joins that comment's parent's replies instead, as on Reddit, so threads never grow too deep to show. COMMENTS_MAX_DEPTH=0 turns replies off.

The text is stored as written, and must be one to COMMENTS_MAX_LENGTH (10,000) characters long. Errors such as an empty text, a reply to a removed comment, or a guest without an email address are CommentErrors, which render as 422 responses.

Reading threads

Comment::threads reads a page of top-level comments with their replies:

let page = Comment::threads(post)
    .sort(Sort::Best)  // Oldest (default), Newest, or Best: most reactions first
    .depth(3)          // load replies down to depth 3; deeper ones are counted in `more_replies`
    .viewer(&user)     // fill `viewer_reactions`
    .page(2)           // from 1
    .per_page(20)      // 20 by default
    .get()
    .await?;

Replies are sorted the same way as the top-level comments. comment.thread_tree().get() reads the whole thread a comment is in, from its top-level comment, for a "continue this thread" page.

The page serializes like this (abridged):

{
  "threads": [
    {
      "id": 1,
      "visibility": "visible",
      "comment": {
        "id": 1,
        "commentable_type": "post",
        "commentable_id": 1,
        "depth": 0,
        "parent_id": null,
        "author_id": 1,
        "guest_name": null,
        "body": "Great post!",
        "status": "approved",
        "edited_at": null,
        "replies_count": 1,
        "reactions_count": 1,
        "created_at": "2026-12-02T21:33:34.167936Z",
        "author": { "id": 1, "name": "Ann" }
      },
      "reactions": { "like": 1 },
      "viewer_reactions": ["like"],
      "replies": [
        {
          "id": 2,
          "visibility": "deleted",
          "comment": null,
          "reactions": {},
          "viewer_reactions": [],
          "replies": [
            {
              "id": 3,
              "visibility": "visible",
              "comment": { "id": 3, "guest_name": "Eve", "body": "Agreed", "author": null, "...": "..." },
              "reactions": {},
              "viewer_reactions": [],
              "replies": [],
              "more_replies": 0
            }
          ],
          "more_replies": 0
        }
      ],
      "more_replies": 0
    }
  ],
  "page": 1,
  "per_page": 20,
  "total": 1,
  "has_more": false
}

Approved comments are visible. A removed comment that still has replies is deleted, and an unapproved comment with approved replies is hidden: both stay as placeholders with "comment": null, so nothing of their text or author reaches the page, and their replies keep their place. Unapproved comments without approved replies are left out.

Linking to a comment

A notification such as "Bob replied to you" needs a link to one comment, on the page that shows it. locate finds that page, with the same sort, page size, and depth your page uses:

if let Some(place) = Comment::threads(post.clone()).sort(Sort::Best).depth(3).locate(&reply).await? {
    // `cut_at`: the reply is deeper than the page loads, so link to the "more replies" above it.
    let anchor = place.cut_at.unwrap_or(place.comment_id);
    let url = format!("/posts/{}?sort=best&page={}#comment-{anchor}", post.id, place.page);
}

One query counts the threads before the comment's thread, so the page is right for the order at the time of the click. locate returns None when the comment's thread isn't on those pages, such as for a pending comment with nothing approved in its thread.

For anything else, Comment::on(post) is a regular query on every comment of a model, in any status, and Comment is a regular model: with, filter, and paginate all work.

Moderation

Each comment has a status: pending, approved, spam, or rejected. Only approved comments are shown. By default, comments by users are approved at once and guests' comments wait (COMMENTS_AUTO_APPROVE=users); everyone and nobody are the other choices.

For anything smarter, give the provider a rule. It sees each new comment and returns its status:

use laravel_comments::{CommentsServiceProvider, NewComment, Status};

providers.add(CommentsServiceProvider::new().moderate_with(async |comment: NewComment| {
    if comment.body.contains("casino") {
        return Ok(Status::Spam);
    }
    let trusted = match comment.author_id {
        Some(id) => User::find(id).await?.is_some_and(|user| user.email_verified_at.is_some()),
        None => false,
    };
    Ok(if trusted { Status::Approved } else { Status::Pending })
}));

Moderators work through the queue:

for mut comment in Comment::pending().limit(50).get().await? {
    comment.approve().await?;   // or reject(), mark_spam(), set_status(..)
}

Each change sets moderated_at, keeps the parent's replies_count right, and dispatches CommentModerated, plus CommentApproved for an approval. Who may moderate is your application's call: check it in your handler or policy.

Editing and removing

comment.edit("Fixed a typo").await?;   // sets `edited_at`
let placeholder = comment.remove().await?;

Each edit keeps the text it replaces, for moderators and "show edits" links:

let earlier: Vec<CommentRevision> = comment.revisions().get().await?; // newest first

COMMENTS_REVISIONS=false stops keeping them.

Removing a comment never breaks a thread. A comment with replies becomes a placeholder: its text, author, guest details, earlier texts, and mentions are cleared, deleted_at is set, and its replies stay where they were. A comment without replies is deleted, together with its reactions, and so is every placeholder above it that has no replies left. remove returns whether a placeholder stays.

Comments aren't removed when the model they belong to is: decide what your application wants, such as Comment::on(post).delete() in the post's deleting hook.

Reactions

Allow the reactions you want, like by default:

COMMENTS_REACTIONS=like,heart,laugh
comment.react(&user, "like").await?;            // false if the user already liked it
comment.unreact(&user, "like").await?;          // false if there was nothing to take back
comment.toggle_reaction(&user, "heart").await?; // whether the reaction is there now

Each user leaves at most one reaction of each kind on a comment, also when the same request comes in twice at once: a unique index lets one of them through. Counts live in comment_reaction_counts and in the comment's reactions_count, changed in the same transaction as the reaction, so pages never count rows. A page of threads carries reactions and, with .viewer(..), viewer_reactions; for your own lists there are reaction_counts(&ids) and reactions_of(user_id, &ids), one query each.

Only approved comments take reactions.

Counting comments

With the #[morph_many(.., filter = Comment::where_visible())] relation from the quick start, with_count counts every visible comment of each post, replies included, in the same query:

let posts = Post::query().with_count(Post::comments).get().await?;
let count = posts[0].comments.count();

Mentions

Tell the provider how to find users by name, and @name in a comment mentions them:

providers.add(CommentsServiceProvider::new().mentions_with(async |names: Vec<String>| {
    User::query().filter(User::username.is_in(names)).pluck(User::id).await
}));

The rule gets the names, lowercased, and returns the users' keys. An @ inside a word, as in an email address, doesn't count, nor does anything in `code`; a trailing . or - ends the sentence, not the name. laravel_comments::mentions(text) shows what a text mentions.

Each mentioned user gets one UserMentioned event, once the comment is visible: at posting when it's approved, at its approval otherwise, or when an edit adds the mention. Approving a comment again, or editing it without new mentions, announces nobody twice. Authors don't mention themselves. Sending the notification is your listener's job:

#[listener]
pub async fn notify_mentioned(event: Event<UserMentioned>) -> laravel::Result<()> {
    let user = User::find_or_fail(event.user_id).await?;
    // Mail the user, or store a notification...
    Ok(())
}

Who may do what

comment_policy! declares a policy with sensible defaults:

laravel_comments::comment_policy! {
    pub struct CommentPolicy for Comment
}
Ability Who
update The author, within COMMENTS_EDIT_WINDOW minutes of posting (no limit by default), and moderators; nobody on a removed comment
delete The author and moderators
reply Anyone, on an approved comment that isn't removed
moderate Moderators

Moderators are the users whose Commenter::is_moderator returns true:

impl Commenter for User {
    fn commenter_id(&self) -> i64 {
        self.id
    }

    fn is_moderator(&self) -> bool {
        self.role == Role::Admin
    }
}

Check the abilities as any policy's: user.authorize(CommentPolicy::update, &comment).await?. For other rules, write the policy yourself and call laravel_comments::abilities::can_edit and the other functions where the defaults suit you.

Rate limiting

throttle counts a comment against COMMENTS_RATE_LIMIT comments a minute (10 by default): users by their key, guests by their IP address. Over the limit, it fails with Laravel Rust's TooManyAttempts, a 429 response with Retry-After:

pub async fn store(post: Post, Authenticated(user): Authenticated<User>, request: Request) -> laravel::Result<Json<Comment>> {
    laravel_comments::throttle(Author::user(&user), request.ip()).await?;
    // Validate and post...
}

Markdown

With the markdown feature, comments may be written in Markdown and shown as safe HTML:

laravel-comments = { version = "0.3", features = ["markdown"] }

comment.body_html() and laravel_comments::markdown::to_html(text) render it, and each visible node of a thread page carries body_html. The text is still stored as written. Raw HTML in it shows as text, links keep only http, https, and mailto addresses and get rel="nofollow ugc noopener noreferrer", and images are dropped, so a comment can't load anything into the page; ammonia cleans the result. The package's tests try twenty kinds of script and request injection on it. In a template, print it as it is: {{ node.body_html|safe }}.

Events

Event When Fields
CommentPosted A comment or reply was posted comment_id, commentable_type, commentable_id, parent_id, author_id, status
CommentModerated A moderator changed the status comment_id, commentable_type, commentable_id, from, to
CommentApproved A moderator approved a comment comment_id, commentable_type, commentable_id
CommentEdited The text was edited comment_id, commentable_type, commentable_id, status
CommentDeleted A comment was removed comment_id, commentable_type, commentable_id, placeholder, status
ReactionAdded Someone reacted comment_id, commentable_type, commentable_id, user_id, reaction
ReactionRemoved Someone took a reaction back comment_id, commentable_type, commentable_id, user_id, reaction
UserMentioned A visible comment mentions a user comment_id, commentable_type, commentable_id, user_id, author_id

They're in laravel_comments::events and carry keys, so a listener loads what it needs:

use laravel::event::{Event, listener};
use laravel_comments::events::CommentPosted;

#[listener]
pub async fn notify_the_author(event: Event<CommentPosted>) -> laravel::Result<()> {
    let Some(parent_id) = event.parent_id else { return Ok(()) };
    // Load the parent comment and email its author...
    Ok(())
}

Broadcasting

To update open pages live, broadcast the events with Laravel Rust's broadcasting:

COMMENTS_BROADCAST=private   # or public; off by default

Each event then broadcasts on the channel of the model its comment belongs to, comments.{commentable_type}.{commentable_id}, such as private-comments.post.42. Authorize the private channel as any other. Events about a comment nobody else may see yet, such as a pending reply or its edits, don't broadcast, and no broadcast carries a comment's text: a page that hears one reloads the thread it shows. UserMentioned never broadcasts.

Drawing the UI yourself

Pass a page to a view: view("comments.thread", data! { page }). This MiniJinja template draws it, replies included, with a recursive loop. The package's tests render it, so it stays in step with the JSON:

{% for node in page.threads recursive %}
<article id="comment-{{ node.id }}">
  {% if node.visibility == "visible" %}
    {% set comment = node.comment %}
    <header>
      <strong>{{ comment.author.name if comment.author else comment.guest_name }}</strong>
      {% if comment.edited_at %}<small>edited</small>{% endif %}
    </header>
    <p>{{ comment.body }}</p>
    <footer>
      {% for reaction, count in node.reactions|items %}
        <button class="{{ 'mine' if reaction in node.viewer_reactions }}">{{ reaction }} {{ count }}</button>
      {% endfor %}
    </footer>
  {% elif node.visibility == "deleted" %}
    <p class="placeholder">This comment was removed.</p>
  {% else %}
    <p class="placeholder">This comment is hidden.</p>
  {% endif %}
  {% if node.replies %}<div class="replies">{{ loop(node.replies) }}</div>{% endif %}
  {% if node.more_replies %}<a href="/comments/{{ node.id }}">{{ node.more_replies }} more replies</a>{% endif %}
</article>
{% endfor %}

With Inertia, pass the page as a prop and render threads with a recursive component; with htmx, return the rendered thread for the part of the page that changed.

Configuration

Variable Default Meaning
COMMENTS_MAX_DEPTH 8 The deepest level a reply sits at; 0 turns replies off
COMMENTS_MAX_LENGTH 10000 The most characters a comment may have
COMMENTS_REACTIONS like The reactions people may leave, separated by commas
COMMENTS_AUTO_APPROVE users Which new comments are approved at once: everyone, users, or nobody
COMMENTS_EDIT_WINDOW 0 For how many minutes authors may edit, by the default policy; 0 for no limit
COMMENTS_RATE_LIMIT 10 How many comments an author may post a minute, by throttle; 0 for no limit
COMMENTS_REVISIONS true Whether to keep the text before each edit
COMMENTS_BROADCAST off Whether the events broadcast: off, public, or private

You may also change them in src/app.rs:

use laravel_comments::CommentsConfig;

Application::configure().with_config(|config, _| {
    config.section_mut::<CommentsConfig>().reactions = vec!["like".into(), "heart".into()];
})

How it works

  • One tree per thread. Each top-level comment starts a nested set of its own, keyed by the thread column, so a reply only shifts the bounds of its own thread and only locks that thread. A busy post's threads never wait for each other, and a thread is read with one indexed query.
  • Counters in columns. replies_count, reactions_count, and comment_reaction_counts change in the same transaction as the change they count, with UPDATE .. SET count = count + 1, so concurrent changes add up and pages read numbers instead of counting rows.
  • A fixed number of queries per page. Counting threads, the top-level comments, their authors, the replies, their authors, the reaction counts, and the viewer's reactions: seven queries for any number of comments. The package's tests check the number.
  • No deadlocks between threads. On PostgreSQL a reply locks its thread with an advisory lock, and on MySQL, with the mysql feature, with a named lock, writing rows by key so InnoDB takes no gap locks. Reactions to one comment take turns on its row. Should the database still abort a write for a deadlock, it runs again, up to five times; inside a transaction of your own it runs once, since only the outermost transaction can retry.
  • Your model, generated. comment_model! writes a plain Laravel Rust model with #[morph_to] commentable and #[belongs_to] author, and implements CommentModel and laravel_nestedset::NestedSet for it. If you need extra columns, write the model yourself and implement both traits as the macro does.

Roadmap

  • Later, if people ask: reports and bans; pinned comments; closing a thread; ranking by Wilson score.

Testing

Tests run in Docker, nothing is installed on the host. SQLite runs in memory:

docker run --rm -v "$PWD":/app -w /app rust:1.99 cargo test

PostgreSQL and MySQL run from docker-compose.yml:

docker compose up -d
docker run --rm --network host -v "$PWD":/app -w /app \
    -e COMMENTS_TEST_POSTGRES_URL=postgres://postgres:secret@127.0.0.1:55432/postgres \
    -e COMMENTS_TEST_MYSQL_URL=mysql://root:secret@127.0.0.1:53306/comments \
    rust:1.99 cargo test --features postgres,mysql,markdown

License

Licensed under either of

at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.