Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Commentable Laravel Package

alibayat/laravel-commentable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require alibayat/laravel-commentable
    php artisan vendor:publish --provider="AliBayat\LaravelCommentable\CommentableServiceProvider"
    php artisan migrate
    

    Verify the comments and commentable tables exist in your database.

  2. Enable on a Model: Add the Commentable trait to your Eloquent model (e.g., Post.php):

    use AliBayat\LaravelCommentable\Commentable;
    
    class Post extends Model
    {
        use Commentable;
    }
    
  3. First Use Case: Create a comment on a model instance:

    $post = Post::find(1);
    $user = User::find(1);
    $post->comment(['body' => 'First comment'], $user);
    

Implementation Patterns

Core Workflows

  1. Comment Creation:

    • Top-Level Comments:
      $model->comment($data, $user); // $data = ['body' => '...', 'title' => '...']
      
    • Nested Comments (Replies):
      $parentComment = Comment::find(1);
      $model->reply($data, $user, $parentComment);
      
    • Bulk Comments: Use a loop or collect() to attach multiple comments at once.
  2. Querying Comments:

    • Fetch all comments for a model:
      $comments = $model->comments()->with('user')->get();
      
    • Fetch replies for a specific comment:
      $replies = $comment->replies()->with('user')->get();
      
    • Filter by user or status:
      $model->comments()->where('user_id', $user->id)->approved()->get();
      
  3. Moderation:

    • Approve/reject comments:
      $comment->approve(); // or $comment->reject()
      
    • Soft-delete comments:
      $comment->delete(); // Uses Laravel's soft-deletes
      
  4. Event Listeners:

    • Listen for comment events (e.g., CommentCreated, CommentApproved):
      use AliBayat\LaravelCommentable\Events\CommentCreated;
      
      CommentCreated::listen(function ($comment) {
          // Send notification, log, etc.
      });
      

Integration Tips

  • APIs: Use apiResources to structure comment responses:
    $comment = $model->comments()->with('user', 'replies.user')->first();
    
  • Frontend: Fetch comments via API and render nested replies recursively (e.g., using Vue/React components).
  • Validation: Extend the package’s validation by overriding the validateComment method in your model:
    public function validateComment($data)
    {
        return validator($data, [
            'body' => 'required|min:10',
            'title' => 'nullable|max:255',
        ]);
    }
    
  • Notifications: Trigger notifications on comment events (e.g., CommentCreated):
    event(new CommentCreated($comment));
    

Gotchas and Tips

Pitfalls

  1. Migration Conflicts:

    • If you’ve manually created a comments table, drop it before publishing migrations to avoid conflicts.
    • The package assumes commentable_id and commentable_type columns in the comments table (polymorphic relations).
  2. Soft Deletes:

    • Ensure your Comment model uses SoftDeletes if you want to soft-delete comments:
      use Illuminate\Database\Eloquent\SoftDeletes;
      
      class Comment extends Model
      {
          use SoftDeletes;
      }
      
    • The delete() method on comments will respect this.
  3. Nested Comment Depth:

    • The package doesn’t enforce a depth limit for replies. If needed, add validation:
      public function reply($data, $user, $parentComment = null, $depth = 0)
      {
          if ($depth >= 3) {
              throw new \Exception('Maximum reply depth reached.');
          }
          // ...
      }
      
  4. User Association:

    • The user_id field in the comments table is required. Ensure your $user variable is always valid before calling comment() or reply().
  5. Polymorphic Relations:

    • If your model isn’t properly set up for polymorphic relations, comments won’t attach correctly. Verify:
      public function comments()
      {
          return $this->morphMany(Comment::class, 'commentable');
      }
      

Debugging

  1. Missing Comments:

    • Check if the commentable_id and commentable_type are correctly populated in the comments table.
    • Run php artisan tinker and test:
      $post = Post::find(1);
      $post->comments()->count(); // Should return > 0 if comments exist.
      
  2. Validation Errors:

    • Override the validateComment method in your model to customize validation rules (see Integration Tips).
  3. Event Firing:

    • Ensure events are fired by listening to them in a service provider or controller:
      CommentCreated::listen(function ($comment) {
          Log::info('Comment created:', ['comment_id' => $comment->id]);
      });
      

Extension Points

  1. Custom Comment Model:

    • Extend the Comment model by publishing the config:
      php artisan vendor:publish --provider="AliBayat\LaravelCommentable\CommentableServiceProvider" --tag=config
      
    • Update config/commentable.php to specify a custom model:
      'model' => \App\Models\CustomComment::class,
      
  2. Additional Fields:

    • Add columns to the comments table by modifying the migration:
      Schema::table('comments', function (Blueprint $table) {
          $table->string('ip_address')->nullable();
          $table->boolean('is_edited')->default(false);
      });
      
    • Update the Comment model to fill these fields:
      protected $fillable = ['body', 'title', 'ip_address'];
      
  3. Custom Scopes:

    • Add scopes to the Comment model for reusable queries:
      public function scopeRecent($query)
      {
          return $query->orderBy('created_at', 'desc')->limit(10);
      }
      
    • Use them like this:
      $model->comments()->recent()->get();
      
  4. Rate Limiting:

    • Implement rate limiting for comments (e.g., using throttle middleware):
      Route::middleware(['throttle:5,1'])->group(function () {
          Route::post('/posts/{post}/comments', [PostController::class, 'store']);
      });
      
  5. Localization:

    • Translate comment-related text (e.g., validation errors) by publishing the language files:
      php artisan vendor:publish --provider="AliBayat\LaravelCommentable\CommentableServiceProvider" --tag=lang
      
    • Override translations in resources/lang/{locale}/commentable.php.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours