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

Commentbundle Laravel Package

atm/commentbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require atm/commentbundle
    

    Add to config/bundles.php:

    return [
        // ...
        Atm\CommentBundle\AtmCommentBundle::class => ['all' => true],
    ];
    
  2. Publish Assets

    php artisan atm:comment:install
    

    This creates:

    • Database migrations (database/migrations/..._create_comments_table.php)
    • Configuration (config/atm_comment.php)
    • Views (resources/views/vendor/atm_comment/)
  3. Run Migrations

    php artisan migrate
    
  4. First Use Case Add a commentable route in your controller:

    use Atm\CommentBundle\Comment\CommentableInterface;
    
    class ArticleController extends Controller implements CommentableInterface
    {
        public function show($id)
        {
            $article = Article::findOrFail($id);
            return view('articles.show', [
                'article' => $article,
                'comments' => $article->comments, // Automatically loaded via trait
            ]);
        }
    }
    
  5. Enable Comments in Blade

    @include('atm_comment::partials/comment_form', ['commentable' => $article])
    @include('atm_comment::partials/comment_list', ['commentable' => $article])
    

Implementation Patterns

Core Workflows

1. Commentable Models

Extend Atm\CommentBundle\Comment\CommentableTrait in your Eloquent models:

use Atm\CommentBundle\Comment\CommentableTrait;

class Article extends Model
{
    use CommentableTrait;
    // ...
}
  • Automatically adds comments() relationship.
  • Provides $commentableType and $commentableId for polymorphic comments.

2. Customizing Comment Forms

Override the default form by publishing views:

php artisan vendor:publish --tag=atm_comment.views

Modify resources/views/vendor/atm_comment/partials/comment_form.blade.php.

3. Validation Rules

Extend validation in config/atm_comment.php:

'validation' => [
    'rules' => [
        'content' => 'required|string|min:10',
        'parent_id' => 'nullable|exists:comments,id',
    ],
    'messages' => [
        'content.required' => 'Your comment cannot be empty!',
    ],
],

4. Nested Comments (Threads)

Enable threading in config:

'threading' => [
    'enabled' => true,
    'max_depth' => 5,
],

Use reply() method in Blade:

@include('atm_comment::partials/comment_reply_form', ['comment' => $comment])

5. API Integration

Use the CommentController or create a custom API endpoint:

use Atm\CommentBundle\Http\Controllers\CommentController as BaseCommentController;

class ApiCommentController extends BaseCommentController
{
    public function __construct()
    {
        $this->middleware('auth:api');
    }
}

6. Event Listeners

Listen to comment events (e.g., CommentCreated):

use Atm\CommentBundle\Events\CommentCreated;

class NotifyModerator
{
    public function handle(CommentCreated $event)
    {
        // Send notification to moderators
    }
}

Register in EventServiceProvider:

protected $listen = [
    CommentCreated::class => [
        NotifyModerator::class,
    ],
];

7. Soft Deletes

Enable soft deletes in config:

'soft_deletes' => true,

Use restore() and forceDelete() on comments.


Integration Tips

Laravel Scout Integration

Add search functionality:

use Atm\CommentBundle\Scout\CommentScout;

class Article extends Model
{
    use CommentableTrait, CommentScout;
    // ...
}

Notification System

Trigger notifications on new comments:

use Atm\CommentBundle\Notifications\NewCommentNotification;

// In your controller
event(new CommentCreated($comment));
$comment->commentable->notify(new NewCommentNotification($comment));

Frontend Frameworks (Vue/React)

Fetch comments via API:

// Vue example
this.comments = await axios.get(`/api/commentables/${this.article.id}/comments`);

Admin Panel

Use Atm\CommentBundle\Http\Controllers\AdminCommentController for moderation:

Route::resource('admin/comments', 'Atm\CommentBundle\Http\Controllers\AdminCommentController');

Gotchas and Tips

Pitfalls

  1. Polymorphic Relationships

    • Issue: Forgetting to set $commentableType and $commentableId manually when not using the trait.
    • Fix: Use Atm\CommentBundle\Comment\Comment::create([...]) with explicit type/ID:
      Comment::create([
          'content' => 'Test',
          'commentable_type' => Article::class,
          'commentable_id' => $article->id,
      ]);
      
  2. Caching Comments

    • Issue: Comments not updating if cached (e.g., with() in eager loading).
    • Fix: Disable caching for commentable models or use fresh():
      $article = Article::with('comments')->find($id);
      $article->comments()->fresh(); // Force reload
      
  3. Threading Depth

    • Issue: Infinite recursion in nested comments if max_depth is too high.
    • Fix: Set a reasonable limit (e.g., 3-5) in config.
  4. Permission Denied

    • Issue: 403 errors when submitting comments without proper middleware.
    • Fix: Add middleware to routes:
      Route::post('/comments', 'CommentController@store')->middleware('auth');
      
  5. Database Locking

    • Issue: Slow performance with high comment volume due to locks.
    • Fix: Use database transactions sparingly or optimize queries:
      DB::connection()->disableQueryLog();
      // Comment operations
      DB::connection()->enableQueryLog();
      
  6. CSRF Token Mismatch

    • Issue: Form submissions failing with CSRF errors in AJAX.
    • Fix: Include CSRF token in meta tags or headers:
      @csrf
      
      Or for AJAX:
      headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
      

Debugging Tips

  1. Query Logging Enable Laravel debug mode:

    APP_DEBUG=true
    

    Check queries in storage/logs/laravel.log.

  2. Commentable Model Check Verify the model implements CommentableInterface:

    class Article implements CommentableInterface { ... }
    
  3. Middleware Order Ensure Atm\CommentBundle\Http\Middleware\VerifyCommentable is loaded before auth middleware.

  4. Event Debugging Listen for events in tinker:

    php artisan tinker
    >>> event(new \Atm\CommentBundle\Events\CommentCreated($comment));
    
  5. View Overrides Clear cached views after publishing:

    php artisan view:clear
    

Extension Points

  1. Custom Comment Models Extend Atm\CommentBundle\Entity\Comment:

    class CustomComment extends Comment
    {
        protected $table = 'custom_comments';
    }
    

    Update config:

    'model' => Atm\CommentBundle\Entity\CustomComment::class,
    
  2. Custom Storage Override storage engine (e.g., Redis):

    use Atm\CommentBundle\Comment\CommentRepositoryInterface;
    
    class RedisCommentRepository implements CommentRepositoryInterface
    {
        // Implement storage logic
    }
    

    Bind in ServiceProvider:

    $this->app->bind(
        CommentRepositoryInterface::class,
        RedisCommentRepository::class
    );
    
  3. Custom Validation Create a custom validator:

    use Atm\CommentBundle\Validation\CommentValidatorInterface;
    
    class CustomCommentValidator implements CommentValidatorInterface
    {
        public function validate(array $data, $commentable)
        {
            // Custom logic
            return $data;
        }
    }
    

    Bind in config:

    'validator' => Atm\CommentBundle\Validation\CustomCommentValidator::class,
    
  4. **Custom Not

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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware