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

Commentable Laravel Package

rostami/commentable

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require rostami/commentable
    

    Publish the migration and config:

    php artisan vendor:publish --provider="Rostami\Commentable\CommentableServiceProvider"
    php artisan migrate
    
  2. Usage on a Model Add the Commentable trait to your Eloquent model:

    use Rostami\Commentable\Commentable;
    
    class Post extends Model
    {
        use Commentable;
    }
    
  3. First Comment Attach comments to a model instance:

    $post = Post::find(1);
    $post->comments()->create([
        'user_id' => auth()->id(),
        'body' => 'This is a great post!',
    ]);
    
  4. Display Comments Retrieve comments via the relationship:

    $comments = $post->comments()->with('user')->get();
    

Key Files to Review

  • config/commentable.php (for customization)
  • app/Models/Comment.php (default comment model)
  • database/migrations/ (schema for comments table)

Implementation Patterns

Core Workflows

  1. Commenting on Models

    // Create a comment
    $model->comments()->create($validatedData);
    
    // Bulk creation (e.g., from a form)
    $model->comments()->createMany($request->comments);
    
  2. Nested Comments (Threads)

    // Reply to a comment
    $comment->replies()->create([
        'user_id' => auth()->id(),
        'body' => 'Thanks for your input!',
        'parent_id' => $comment->id, // Explicitly set parent
    ]);
    
  3. Querying Comments

    // Get top-level comments (non-replies)
    $model->comments()->whereNull('parent_id')->get();
    
    // Get a comment thread (recursive)
    $comment->load('replies.user');
    
  4. Soft Deletes

    // Delete a comment (soft delete)
    $comment->delete();
    
    // Restore a comment
    $comment->restore();
    

Integration Tips

  • Validation: Use Laravel’s validation to sanitize comment bodies (e.g., max:1000, string).
  • Authorization: Gate comment actions (e.g., can('delete', $comment)).
  • Events: Listen for CommentCreated, CommentDeleted events for notifications.
  • APIs: Use api_resources to structure comment responses:
    $comment->load('user', 'replies.user');
    return new CommentResource($comment);
    

Common Extensions

  1. Custom Comment Model Override the default Comment model in config/commentable.php:

    'model' => App\Models\CustomComment::class,
    
  2. Additional Fields Add fields to the comments table via migration, then update the Comment model’s $fillable.

  3. Scopes Add query scopes to the Comment model:

    public function scopeApproved($query)
    {
        return $query->where('approved', true);
    }
    

Gotchas and Tips

Pitfalls

  1. Missing Migration If you forget to run php artisan migrate, comments will fail to save. Always check the comments table exists.

  2. Parent-Child Relationships

    • Gotcha: Forgetting to set parent_id when replying creates a top-level comment.
    • Fix: Use reply() helper if provided:
      $comment->reply($request->body);
      
  3. Circular References

    • Gotcha: Eager-loading replies recursively can cause N+1 queries or stack overflows.
    • Fix: Limit depth or use withCount('replies') for metrics.
  4. Soft Deletes Confusion

    • Gotcha: delete() soft-deletes comments but may not update UI if not handled in frontend.
    • Fix: Use Comment::withTrashed() to fetch soft-deleted comments.
  5. User Association

    • Gotcha: Assuming user_id is always set (e.g., for anonymous comments).
    • Fix: Add nullable user_id to the migration or handle null cases in logic.

Debugging Tips

  • Check Relationships:
    dd($model->comments()->getQuery()->toSql());
    
  • Verify Config:
    dd(config('commentable'));
    
  • Test with Tinker:
    php artisan tinker
    $post = App\Post::first();
    $post->comments()->create(['body' => 'Test']);
    

Performance Quirks

  1. Bulk Operations Avoid bulk creating comments in loops; use createMany() instead.

  2. Caching Cache comment counts or threads if frequently accessed:

    $commentCount = Cache::remember("comments_{$model->id}", now()->addHours(1), function() {
        return $model->comments()->count();
    });
    
  3. Database Indexes Add indexes to user_id, parent_id, and commentable_id for large datasets:

    Schema::table('comments', function (Blueprint $table) {
        $table->index('user_id');
        $table->index('parent_id');
        $table->index('commentable_id');
    });
    

Extension Points

  1. Custom Commentable Types Extend the Commentable trait to support polymorphic relationships (e.g., comments on Post, Video):

    class Commentable
    {
        public function comments()
        {
            return $this->morphMany(Comment::class, 'commentable');
        }
    }
    
  2. Comment Moderation Add approved column and use model observers:

    class CommentObserver
    {
        public function saving(Comment $comment)
        {
            if (!$comment->approved && $comment->isDirty('approved')) {
                // Trigger notification
            }
        }
    }
    
  3. Comment Notifications Use Laravel Notifications to alert users when replied to:

    $comment->user->notify(new CommentReplyNotification($comment));
    
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.
boundwize/pyrameter
testo/facade
headercat/phpstan-extension-ide-helper
yosymfony/parser-utils
innmind/black-box
babenkoivan/elastic-migrations
babenkoivan/elastic-adapter
sandermuller/package-boost-php
sandermuller/boost-core
develia/commons
dmstr/symfony-system-resources-bundle
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
renatomarinho/laravel-page-speed
develia/geo-bundle
austinheap/laravel-database-encryption
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
imbo/imbo-coding-standard