›
byrcsc/laravel-comments · 1.x
Add comments, replies, moderation, and safe rendering to an Eloquent model.
This walkthrough adds a moderated comment thread to a Post. It assumes
Laravel Comments is installed.
Add the HasComments trait:
use ByRcsc\LaravelComments\Concerns\HasComments;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasComments;
}The model now has a comments() relationship and methods for authenticated and
guest comments.
$comment = $post->comment('Great write-up!', by: $user);
$reply = $comment->reply(
'Agreed, especially the last section.',
by: $teammate,
);The by argument accepts any saved Eloquent model. Laravel Comments stores the
actor through a polymorphic relationship and does not require
App\Models\User.
Replies remain attached to the same commentable model as their parent:
$reply->parent_id; // the first comment's key
$reply->depth(); // 1$guest = $post->commentAsGuest(
'Where can I download the slides?',
name: 'Jane',
email: 'jane@example.com',
);
$guest->status; // CommentStatus::Pending
$guest->approve(by: $moderator);Guest comments always start as pending. Approving changes the stored status
and dispatches a moderation event.
Status does not control visibility by itself. Your query decides which comments appear to visitors.
Load approved top-level comments and their direct replies:
$threads = $post->comments()
->approved()
->topLevel()
->with('replies')
->get();Render comment bodies with escaped Blade output:
{{ $comment->body }}Laravel Comments stores bodies and guest details exactly as received. Sanitize the value before rendering it as Markdown or HTML.