Comments will be always be associated with Eloquent models. To allow an Eloquent model to have comments associated with it, use the Spatie\Comments\HasComments
trait on it.
use Illuminate\Database\Eloquent\Model;
use Spatie\Comments\Models\Concerns\HasComments;
class Post extends Model
{
use HasComments;
}
To create a new comment, you can call the comment
method.
$post->comment("I've got a feeling");
Behind the scene new Spatie\Comments\Comment
model will be saved. The comment will be associated with the $post
and the currently logged in user.
You can associate the comment with another user, by passing it as a second argument.
$anotherUser = User::whereFirst('email', 'paul@beatles.com');
$post->comment("I've got a feeling", $anotherUser);
Because the Comment
model itself uses the HasComments
trait, you can create a nested comment like by calling comment
on a Comment
.
$comment = $post->comment("I've got a feeling");
$nestedComment = $comment->comment("It keeps me on my toes")
##Handling markdown and other formats
To add support for markdown, take a look at the section on transforming comments.
To get all comments of a model, use the comments
relationship.
$allComments = $post->comments;
You can get all unnested comments like this:
$unnestedComments = $post->comments()->topLevel()->get();
To update the content of a comment, update the orginal_property
attribute of a comments model.
$comment->update([
'original_text' => 'Updated comment',
]);
Simply call delete
on a Comment
model.
$comment->delete();
You can use the commentator
relationship to determine who made a comment.
$user = $comment->commentator
If the user that made the comment was deleted, or that comment was made anonymously, then $comment->commentator
will return null
.
You can use these methods to determine why there was no commentator found.
$comment->wasMadeByDeletedCommentator();
$comment->wasMadeAnonymously();