Customization
Define custom policies and listen to comment events.
Custom policy
You can define a custom policy for the Comment model to control who can create, update, reply, or delete comments. First, create a new policy class (for example, App\Policies\CommentPolicy) and extend the default policy:
namespace App\Policies;
use Tilto\Commentable\Contracts\Commenter;
use Tilto\Commentable\Models\Comment;
use Tilto\Commentable\Policies\CommentPolicy as CommentablePolicy;
class CommentPolicy extends CommentablePolicy
{
public function create(Commenter $user): bool
{
// ...
}
public function update(Commenter $user, Comment $comment): bool
{
// ...
}
public function reply(Commenter $user, Comment $comment): bool
{
// ...
}
public function delete(Commenter $user, Comment $comment): bool
{
// ...
}
}
Then, update the comment.policy value in your config/commentable.php file to point to your new policy:
'comment' => [
'model' => Tilto\Commentable\Models\Comment::class,
'policy' => App\Policies\CommentPolicy::class,
],
This allows you to fully customize comment permissions to fit your application's requirements.
Listening for comment creation events
To perform actions when a comment is created, listen for the CommentCreatedEvent in your event listener. This allows you to trigger notifications, logging, or other custom logic whenever a new comment is added.
Here's an example of how to set up a listener for the event:
use Tilto\Commentable\Events\CommentCreatedEvent;
class NotifyOnCommentCreated
{
public function handle(CommentCreatedEvent $event): void
{
// Access the created comment:
$comment = $event->comment;
// Add your custom logic here, e.g., send a notification
}
}
If you don't have event auto-discovery turned on in Laravel, you will need to manually register your listener within your EventServiceProvider:
protected $listen = [
CommentCreatedEvent::class => [
NotifyOnCommentCreated::class,
],
];

