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 Admin Panel Laravel Package

lakm/laravel-comments-admin-panel

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require lakm/laravel-comments-admin-panel
    php artisan vendor:publish --provider="Lakm\CommentsAdminPanel\CommentsAdminPanelServiceProvider"
    php artisan migrate
    
    • Publishes config, migrations, and views to config/comments-admin-panel.php and resources/views/vendor/comments-admin-panel/.
  2. First Use Case

    • Register the admin panel route in routes/web.php:
      Route::middleware(['auth:sanctum', 'admin'])->group(function () {
          Route::resource('comments', \Lakm\CommentsAdminPanel\Http\Controllers\CommentController::class);
      });
      
    • Ensure admin middleware is defined (e.g., via Gate::before() or a custom middleware).
  3. Model Discovery

    • Configure config/comments-admin-panel.php to specify which models support comments:
      'models' => [
          \App\Models\Post::class,
          \App\Models\Article::class,
      ],
      
    • Run php artisan comments-admin-panel:discover to auto-detect commentable models (if using traits).

Implementation Patterns

Core Workflows

  1. CRUD Operations

    • The package provides a scaffolded CommentController with methods for:
      • Listing comments (index): Supports pagination, filtering by model, and status.
      • Showing a single comment (show): Includes related commentable model data.
      • Editing (edit/update): Soft-deletes, replies, and moderation actions.
      • Destroying (destroy): Soft-deletes by default (configurable).
    • Example Filtering:
      // Filter comments by model and status
      $comments = $this->commentRepository->getComments([
          'commentable_type' => \App\Models\Post::class,
          'status' => 'approved',
      ]);
      
  2. Model Integration

    • Commentable Models: Use the Commentable trait or manually define relationships:
      use Lakm\Comments\Traits\Commentable;
      
      class Post extends Model
      {
          use Commentable;
          // ...
      }
      
    • Custom Fields: Extend the Comment model or use the CommentController to add custom logic:
      // Override the controller to add custom fields
      public function update(Request $request, Comment $comment) {
          $validated = $request->validate([
              'content' => 'required',
              'custom_field' => 'nullable|string',
          ]);
          $comment->update($validated);
      }
      
  3. Authorization

    • Use Laravel’s gates/policies to restrict access:
      Gate::define('manage-comments', function (User $user) {
          return $user->isAdmin();
      });
      
    • Attach middleware to routes:
      Route::middleware(['auth:sanctum', 'can:manage-comments'])->group(...);
      
  4. API Integration

    • The package includes API endpoints for comments (if API_ENABLED=true in config). Example:
      Route::apiResource('comments', \Lakm\CommentsAdminPanel\Http\Controllers\Api\CommentController::class);
      

Advanced Patterns

  1. Dynamic Model Binding

    • Use route model binding to fetch commentable models dynamically:
      Route::get('/comments/{commentable}', [CommentController::class, 'index'])
           ->name('comments.index');
      
    • Bind the commentable parameter in the controller:
      public function index(Commentable $commentable) {
          return $this->commentRepository->getCommentsFor($commentable);
      }
      
  2. Bulk Actions

    • Extend the CommentController to support bulk approval/rejection:
      public function bulkUpdate(Request $request) {
          $request->validate(['status' => 'required|in:approved,rejected']);
          $this->commentRepository->updateStatus($request->ids, $request->status);
      }
      
  3. Event Listeners

    • Listen for comment events (e.g., CommentCreated, CommentApproved) to trigger notifications:
      Comment::created(function (Comment $comment) {
          Notification::route('mail', $comment->user->email)
                      ->notify(new CommentCreatedNotification($comment));
      });
      
  4. Custom Views

    • Override default views by publishing and modifying:
      php artisan vendor:publish --tag=comments-admin-panel-views
      
    • Extend Blade templates (e.g., resources/views/vendor/comments-admin-panel/comments/index.blade.php).

Gotchas and Tips

Pitfalls

  1. Model Discovery Issues

    • Problem: php artisan comments-admin-panel:discover fails to detect models.
    • Fix: Ensure models use the Commentable trait or manually define commentable() in config/comments-admin-panel.php:
      'models' => [
          \App\Models\Post::class => [
              'commentable' => true,
          ],
      ],
      
  2. Soft Deletes Conflicts

    • Problem: Soft-deleted comments reappear after migration.
    • Fix: Run php artisan comments-admin-panel:prune to clean up orphaned records or ensure deleted_at is nullable in the comments table.
  3. Authorization Bypass

    • Problem: Unauthorized users access the admin panel.
    • Fix: Verify middleware in routes/web.php and gates/policies:
      // Ensure this runs before the route group
      Gate::before(function (User $user) {
          if ($user->isAdmin()) {
              return true;
          }
      });
      
  4. Performance with Large Datasets

    • Problem: Slow loading of comments for models with thousands of entries.
    • Fix: Add indexes to commentable_type and commentable_id in the comments table:
      Schema::table('comments', function (Blueprint $table) {
          $table->index(['commentable_type', 'commentable_id']);
      });
      
    • Use eager loading in the controller:
      $comments = Comment::with('commentable')->get();
      

Debugging Tips

  1. Log Query Builder SQL

    • Enable Laravel’s query logging in AppServiceProvider:
      public function boot() {
          if (config('app.debug')) {
              DB::enableQueryLog();
          }
      }
      
    • Dump queries in the controller:
      $comments = $this->commentRepository->getComments([]);
      \Log::debug(DB::getQueryLog());
      
  2. Check Published Config

    • Verify config/comments-admin-panel.php after publishing:
      php artisan config:clear
      
  3. Validate Middleware

    • Test middleware isolation:
      Route::get('/test-auth', function () {
          return "Authorized";
      })->middleware(['auth:sanctum', 'admin']);
      

Extension Points

  1. Custom Repository

    • Extend the default repository to add logic:
      namespace App\Repositories;
      
      use Lakm\CommentsAdminPanel\Repositories\CommentRepository as BaseRepository;
      
      class CommentRepository extends BaseRepository {
          public function getSpamComments() {
              return $this->model->where('status', 'pending')
                                 ->where('content', 'like', '%spam%')
                                 ->get();
          }
      }
      
    • Bind the custom repository in AppServiceProvider:
      $this->app->bind(
          \Lakm\CommentsAdminPanel\Repositories\CommentRepository::class,
          App\Repositories\CommentRepository::class
      );
      
  2. Custom Actions

    • Add buttons to the comment list view:
      @foreach($comments as $comment)
          <td>
              <form action="{{ route('comments.bulk') }}" method="POST">
                  @csrf
                  <input type="hidden" name="ids[]" value="{{ $comment->id }}">
                  <button type="submit" class="btn btn-sm btn-warning">
                      Flag as Spam
                  </button>
              </form>
          </td>
      @endforeach
      
  3. Webhook Integration

    • Trigger external actions on comment events:
      Comment::created(function (Comment $comment) {
          Http::post('https://api.example.com/webhooks/comments', [
              'comment_id' => $comment->id,
          ]);
      });
      
  4. Localization

    • Override default language strings by publishing translations:
      php artisan vendor:publish --tag=comments-admin-panel-lang
      
    • Modify resources/lang/en/comments-admin-panel.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.
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
renatovdemoura/blade-elements-ui