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 Comments Laravel Package

lakm/laravel-comments

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require lakm/laravel-comments
    php artisan vendor:publish --provider="Lakm\Comments\CommentsServiceProvider" --tag="migrations"
    php artisan migrate
    
    • Run migrations to create comments, comment_replies, and comment_votes tables.
  2. Configuration:

    • Publish config file:
      php artisan vendor:publish --provider="Lakm\Comments\CommentsServiceProvider" --tag="config"
      
    • Update config/comments.php with your preferred settings (e.g., model, table_names, moderation).
  3. First Use Case:

    • Display comments on a blog post:
      use Lakm\Comments\Facades\Comments;
      
      // In your controller:
      $comments = Comments::getComments($postId);
      
      // In your Blade view:
      @comments(['model' => $post, 'comments' => $comments])
      
    • Ensure the model (Post in this case) uses the Lakm\Comments\Contracts\Commentable trait.

Implementation Patterns

Core Workflows

  1. Commenting on Models:

    • Use the Commentable trait on any model to enable comments:
      use Lakm\Comments\Contracts\Commentable;
      
      class Post extends Model
      {
          use Commentable;
      }
      
    • Trigger comments via facade or service:
      Comments::create($postId, $userId, 'This is a comment!');
      
  2. Nested Replies:

    • Reply to a comment or reply:
      Comments::reply($commentId, $userId, 'Reply text', $parentReplyId = null);
      
    • Display replies in Blade:
      @comments(['model' => $post, 'comments' => $comments, 'withReplies' => true])
      
  3. Moderation & Approval:

    • Enable moderation in config/comments.php:
      'moderation' => [
          'enabled' => true,
          'default_status' => 'pending',
      ],
      
    • Approve/reject comments via:
      Comments::approve($commentId);
      Comments::reject($commentId, 'Reason');
      
  4. Voting System:

    • Enable voting in config:
      'voting' => [
          'enabled' => true,
          'types' => ['up', 'down'],
      ],
      
    • Cast votes:
      Comments::vote($commentId, 'up', $userId);
      
  5. Theming:

    • Customize the comment view by publishing assets:
      php artisan vendor:publish --provider="Lakm\Comments\CommentsServiceProvider" --tag="public"
      
    • Override default Blade templates in resources/views/vendor/comments/.

Integration Tips

  • API Support: Use the CommentsController provided by the package or extend it:

    use Lakm\Comments\Http\Controllers\CommentsController;
    
    Route::post('/comments', [CommentsController::class, 'store']);
    
  • Real-Time Updates: Pair with Laravel Echo/Pusher for live comment/reply notifications:

    Echo.channel('comments')
        .listen('CommentCreated', (e) => {
            // Update UI
        });
    
  • Soft Deletes: Enable soft deletes in config:

    'soft_deletes' => true,
    

    Then use:

    Comments::restore($commentId);
    Comments::forceDelete($commentId);
    
  • Caching: Cache comment queries for performance:

    $comments = Cache::remember("comments_{$postId}", now()->addHours(1), function () use ($postId) {
        return Comments::getComments($postId);
    });
    

Gotchas and Tips

Pitfalls

  1. Model Trait Conflicts:

    • Ensure Commentable trait is added after other traits (e.g., HasFactory, Notifiable) to avoid method conflicts.
    • If using polymorphic relations, explicitly define commentable_type and commentable_id in the comments table.
  2. Migration Issues:

    • If migrating an existing database, manually adjust the comments table schema to match the package’s expectations (e.g., user_id, commentable_id, status columns).
    • Run php artisan comments:install if migrations fail silently.
  3. Permission Denied:

    • The package assumes users are authenticated. Add middleware:
      Route::middleware(['auth'])->group(function () {
          // Comment routes
      });
      
    • Customize permissions via middleware or policies:
      Comments::setAuthResolver(function () {
          return Auth::user();
      });
      
  4. Nested Reply Depth:

    • Default reply depth is 3 levels. Adjust in config:
      'reply_depth' => 5,
      
    • Deep nesting may impact performance; consider pagination for replies.
  5. Vote Abuse:

    • Without rate-limiting, users can spam votes. Add middleware:
      Route::middleware(['throttle:10,1'])->group(function () {
          // Vote routes
      });
      

Debugging

  1. Query Logging: Enable Laravel’s query logging to debug comment retrieval:

    DB::enableQueryLog();
    $comments = Comments::getComments($postId);
    dd(DB::getQueryLog());
    
  2. Event Debugging: Listen for comment events to trace workflows:

    Comments::on('comment.created', function ($comment) {
        Log::info('New comment:', ['comment' => $comment]);
    });
    
  3. Validation Errors: Customize validation rules in config/comments.php:

    'validation' => [
        'comment' => 'required|string|max:5000',
        'reply' => 'required|string|max:3000',
    ],
    

Extension Points

  1. Custom Fields: Extend the Comment model to add fields:

    class Comment extends \Lakm\Comments\Models\Comment
    {
        protected $casts = [
            'custom_field' => 'boolean',
        ];
    }
    

    Update migrations and config accordingly.

  2. Event Hooks: Subscribe to package events in EventServiceProvider:

    protected $listen = [
        'Lakm\Comments\Events\CommentCreated' => [
            'App\Listeners\LogComment',
        ],
    ];
    
  3. API Resources: Override the default CommentResource:

    class CustomCommentResource extends \Lakm\Comments\Http\Resources\CommentResource
    {
        public function toArray($request)
        {
            $array = parent::toArray($request);
            $array['custom_field'] = $this->custom_field;
            return $array;
        }
    }
    

    Update routes to use your resource.

  4. Testing: Use the package’s test helpers:

    use Lakm\Comments\Testing\CreatesComments;
    
    class CommentTest extends TestCase
    {
        use CreatesComments;
    
        public function testCommentCreation()
        {
            $comment = $this->createComment($postId, $userId, 'Test comment');
            $this->assertDatabaseHas('comments', ['id' => $comment->id]);
        }
    }
    

Config Quirks

  1. Table Names: Customize table names in config:

    'table_names' => [
        'comments' => 'custom_comments',
        'replies' => 'custom_replies',
    ],
    
    • Ensure corresponding migrations are updated.
  2. User Model: Specify a custom user model:

    'user_model' => \App\Models\CustomUser::class,
    
    • The model must implement Illuminate\Contracts\Auth\Authenticatable.
  3. Default Status: Set default comment status (pending, approved, rejected):

    'moderation' => [
        'default_status' => 'pending',
    ],
    
  4. Avatar Handling: Customize avatar logic in config:

    'avatar' => [
        'gravatar' => false,
        'default' => 'https://via.placeholder.com/50',
    ],
    

    Or override the getAvatarUrl() method in the Comment model.


Performance Tips

  1. Eager Loading: Eager-load relationships to avoid N+1 queries:

    $comments = Comments::with(['user', 'replies.user'])->getComments($postId);
    
  2. Pagination: Paginate comments/replies:

    $comments = Comments::getComments($postId)->paginate(10);
    
  3. Caching Strategies: Cache comment counts for models:

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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity