laravel-comments
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
- Installation
- Quick start: comments on blog posts
- Posting and replying
- Reading threads
- Moderation
- Editing and removing
- Reactions
- Counting comments
- Mentions
- Who may do what
- Rate limiting
- Markdown
- Events
- Broadcasting
- Drawing the UI yourself
- Configuration
- How it works
- Roadmap
- Testing
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_atmark, 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
COUNTon 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 @namementions, 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
markdownfeature - 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
Serializevalue for JSON or a template - Tested on SQLite, PostgreSQL, and MySQL, including concurrent likes and replies, and query counts
Installation
[]
= "0.2"
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:
[]
= { = "0.2", = ["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 Application;
configure
.with_providers
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 Commenter;
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 morph;
use crate;
comment_model!
Give Post its comments. The filter counts only the comments everyone may see:
// src/models/post.rs
use ;
use CommentModel;
use crateComment;
Now post, reply, and read:
use Auth;
use *;
use ;
use crate;
/// `POST /posts/{post}/comments`
pub async
/// `POST /comments/{comment}/replies`
pub async
/// `GET /posts/{post}/comments`, for guests and signed-in users
pub async
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 = post.await?;
let from_guest = post.await?;
A reply goes under any approved comment, and reloads the comment it answers:
let reply = comment.reply.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 = threads
.sort // Oldest (default), Newest, or Best: most reactions first
.depth // load replies down to depth 3; deeper ones are counted in `more_replies`
.viewer // fill `viewer_reactions`
.page // from 1
.per_page // 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):
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 = threads.sort.depth.locate.await?
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 ;
providers.add;
Moderators work through the queue:
for mut comment in pending.limit.get.await?
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.await?; // sets `edited_at`
let placeholder = comment.remove.await?;
Each edit keeps the text it replaces, for moderators and "show edits" links:
let earlier: = 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.await?; // false if the user already liked it
comment.unreact.await?; // false if there was nothing to take back
comment.toggle_reaction.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 = query.with_count.get.await?;
let count = posts.comments.count;
Mentions
Tell the provider how to find users by name, and @name in a comment mentions them:
providers.add;
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:
pub async
Who may do what
comment_policy! declares a policy with sensible defaults:
comment_policy!
| 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:
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
Markdown
With the markdown feature, comments may be written in Markdown and shown as safe HTML:
= { = "0.2", = ["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 ;
use CommentPosted;
pub async
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 %}
{% if node.visibility == "visible" %}
{% set comment = node.comment %}
{{ comment.author.name if comment.author else comment.guest_name }}
{% if comment.edited_at %}edited{% endif %}
{{ comment.body }}
{% for reaction, count in node.reactions|items %}
{{ reaction }} {{ count }}
{% endfor %}
{% elif node.visibility == "deleted" %}
This comment was removed.
{% else %}
This comment is hidden.
{% endif %}
{% if node.replies %}{{ loop(node.replies) }}{% endif %}
{% if node.more_replies %}{{ node.more_replies }} more replies{% endif %}
{% 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 CommentsConfig;
configure.with_config
How it works
- One tree per thread. Each top-level comment starts a nested set of its own, keyed by the
threadcolumn, 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, andcomment_reaction_countschange in the same transaction as the change they count, withUPDATE .. 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
mysqlfeature, 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] commentableand#[belongs_to] author, and implementsCommentModelandlaravel_nestedset::NestedSetfor 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
- Apache License, Version 2.0 (LICENSE-APACHE)
- MIT license (LICENSE-MIT)
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.