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

Comment Bundle Laravel Package

dvtrung/comment-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require dvtrung/comment-bundle
    

    Add to config/bundles.php (Symfony) or config/app.php (Laravel via bridge):

    return [
        // ...
        DvTrung\CommentBundle\DvTrungCommentBundle::class => ['all' => true],
    ];
    
  2. Publish Config

    php artisan vendor:publish --provider="DvTrung\CommentBundle\DvTrungCommentBundle" --tag="config"
    

    Edit config/comment.php to define:

    • default_driver (e.g., database, disqus, or custom)
    • Driver-specific configurations (e.g., Disqus API key, database table names).
  3. First Use Case: Database Comments Define a model (e.g., Post) with a comments() relationship:

    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
    

    Create a comment via facade:

    use DvTrung\CommentBundle\Facades\Comment;
    
    $comment = Comment::create([
        'commentable_id' => $post->id,
        'commentable_type' => Post::class,
        'user_id' => auth()->id(),
        'body' => 'Great post!',
    ]);
    
  4. Blade Integration

    @commentable($post)
        @foreach($post->comments as $comment)
            <div>{{ $comment->body }}</div>
        @endforeach
    @endcommentable
    

Implementation Patterns

Driver-Based Workflows

  1. Switching Drivers Dynamically Configure multiple drivers in config/comment.php:

    'drivers' => [
        'database' => [
            'table' => 'comments',
        ],
        'disqus' => [
            'shortname' => 'your-site',
            'api_key' => env('DISQUS_API_KEY'),
        ],
    ],
    

    Use in code:

    Comment::setDriver('disqus')->create([...]);
    
  2. Hybrid Approach (Database + Disqus)

    • Store metadata (e.g., disqus_thread_id) in the database.
    • Use Disqus for frontend rendering, sync replies to DB via webhooks.

Common Use Cases

  1. Threaded Replies

    $reply = Comment::create([
        'parent_id' => $comment->id,
        'body' => 'Thanks for your input!',
    ]);
    
  2. Validation Rules Extend the Comment model or use form requests:

    use DvTrung\CommentBundle\Rules\CommentRules;
    
    $request->validate([
        'body' => ['required', new CommentRules],
    ]);
    
  3. API Endpoints

    Route::post('/posts/{post}/comments', function (Request $request, Post $post) {
        return Comment::create([
            'commentable_id' => $post->id,
            'commentable_type' => Post::class,
            'body' => $request->body,
        ]);
    });
    
  4. Event Listeners Listen for comment creation/deletion:

    Comment::created(function ($comment) {
        // Send notification, log, etc.
    });
    

Integration Tips

  • Laravel-Specific: Use MorphTo for polymorphic relationships if not already set up.
  • Caching: Cache comment threads for high-traffic pages:
    $comments = Cache::remember("comments.{$post->id}", now()->addHours(1), function () use ($post) {
        return $post->comments()->latest()->get();
    });
    
  • Soft Deletes: Enable if using database driver:
    use Illuminate\Database\Eloquent\SoftDeletes;
    
    class Comment extends Model
    {
        use SoftDeletes;
    }
    

Gotchas and Tips

Pitfalls

  1. Driver Mismatches

    • Ensure the commentable_type matches the fully qualified class name (e.g., App\Models\Post).
    • Fix: Use get_morph_class() helper or cast types in config:
      'drivers' => [
          'database' => [
              'morph_map' => [
                  'post' => Post::class,
              ],
          ],
      ],
      
  2. Disqus Webhooks

    • If using Disqus, verify webhook signatures to avoid spoofing:
      use DvTrung\CommentBundle\Services\DisqusWebhook;
      
      $validator = new DisquusWebhook($request->all());
      if (!$validator->isValid()) {
          abort(403);
      }
      
  3. Polymorphic Conflicts

    • Avoid naming collisions with other polymorphic models (e.g., Comment vs. PostComment).
    • Tip: Use a unique commentable_type prefix (e.g., app.Post).
  4. Migration Issues

    • If publishing migrations, ensure the commentable_id and commentable_type columns exist:
      Schema::table('comments', function (Blueprint $table) {
          $table->morphs('commentable');
      });
      

Debugging

  1. Driver-Specific Errors

    • Check config/comment.php for typos in driver names or missing keys.
    • For Disqus, verify API keys and shortnames in Disqus Admin.
  2. Logging Enable debug mode in config/comment.php:

    'debug' => env('APP_DEBUG', false),
    

    Check logs for driver initialization errors.

  3. Common SQL Errors

    • Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'commentable_type' Fix: Run migrations or check table structure.

Extension Points

  1. Custom Drivers Create a new driver by extending DvTrung\CommentBundle\Contracts\DriverInterface:

    namespace App\Drivers;
    
    use DvTrung\CommentBundle\Contracts\DriverInterface;
    
    class SlackDriver implements DriverInterface
    {
        public function create(array $data) { ... }
        public function find($id) { ... }
    }
    

    Register in config/comment.php:

    'drivers' => [
        'slack' => [
            'webhook_url' => env('SLACK_WEBHOOK_URL'),
        ],
    ],
    
  2. Model Events Override model events in a service provider:

    Comment::created(function ($comment) {
        // Custom logic (e.g., send email)
    });
    
  3. Blade Directives Extend the @commentable directive in a service provider:

    Blade::directive('commentable', function ($expr) {
        return "<?php echo \$__env->make('comment::partials.thread', ['commentable' => {$expr}])->render(); ?>";
    });
    

Performance Tips

  • Eager Loading: Avoid N+1 queries:
    $posts = Post::with(['comments' => function ($query) {
        $query->latest()->limit(10);
    }])->get();
    
  • Pagination: Use cursor() for infinite scroll:
    $comments = $post->comments()->latest()->cursor()->paginate(10);
    
  • Database Driver: Add indexes to commentable_type and user_id for large datasets.
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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin