Preparing your models
Add HasComments to anything that can be commented on, and GivesComments to anything that can author a comment (typically your User):
use Illuminate\Database\Eloquent\Model;
use RoundlyConsulting\Comments\Traits\HasComments;
use RoundlyConsulting\Comments\Traits\GivesComments;
class Post extends Model
{
use HasComments;
}
class User extends Model
{
use GivesComments;
}What each trait adds
| Member | Trait | Purpose |
|---|---|---|
comments() | HasComments | Every comment on the model (MorphMany). |
approvedComments() | HasComments | Visible + approved top-level comments, ordered per comments.order. |
threadedComments() | HasComments | The public thread: visible + approved top-level comments with only visible + approved replies, up to max_depth. |
loadCommentCount() | HasComments | Loads comments_count — every visible + approved comment, replies included. |
withCommentCounts() | HasComments | Query scope adding the same public comments_count without N+1. |
commentsLocked() | HasComments | Whether the model’s comment section is locked. |
writtenComments() | GivesComments | Every comment the model authored (MorphMany). |
writeComment() | GivesComments | Write a comment on a subject as this author. |
$post->comments; // every comment on the post
$post->approvedComments; // visible + approved top-level comments, ordered per config
$post->threadedComments; // the public thread: visible + approved roots and replies
$post->commentsLocked(); // bool — is the post's comment section locked?
$user->writtenComments; // every comment the user authored
$user->writeComment($post, 'Great article!');Using your own Comment model
Point comments.model at a subclass of the packaged Comment when you need extra columns, casts or behaviour. The package resolves the model through that key everywhere — writes, relations, replies and the fluent query. Any value that isn’t the packaged Comment or a subclass of it — a missing class, a non-model, an unrelated model — throws an InvalidConfigurationException naming the key; it never silently falls back to the packaged model:
namespace App\Models;
use RoundlyConsulting\Comments\Models\Comment as BaseComment;
class Comment extends BaseComment
{
// extra columns, casts, relations and behaviour
}
// config/comments.php
'model' => App\Models\Comment::class,The packaged Comment already implements HasMedia, Likeable and Reportable and uses soft deletes — so your subclass inherits likes, reports, attachments and everything else.
Show your open-source love
This package is free and MIT-licensed. If it saves you time, a one-off donation or a Patreon membership keeps it maintained, tested and documented.
More ways to support, including cryptoBy donating, you agree to our donation terms.
Want this built into your product?
We integrate our packages into custom Laravel and AI builds. Tell us what you're working on and we'll reply within 48 hours.