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

spatie/laravel-blade-comments

Adds HTML debug comments around every rendered Blade view/component so you can see exactly which template produced each piece of output in browser dev tools. Also includes top-level request and view info at the top of the document.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require spatie/laravel-blade-comments --dev
    
    • Automatically enabled in APP_DEBUG mode (configurable via blade-comments.enable).
    • No additional setup required for basic usage.
  2. First Use Case:

    • Open your browser’s DevTools (e.g., Chrome/Firefox) and inspect any rendered Blade view.
    • Look for HTML comments like:
      <!-- BEGIN: resources/views/layouts/app.blade.php -->
      <!-- END: resources/views/layouts/app.blade.php -->
      
    • These wrap every Blade file, making it trivial to trace rendered HTML back to its source.
  3. Where to Look First:

    • Config File: Publish and review config/blade-comments.php to adjust exclusions or middleware.
    • Middleware: Ensure Spatie\BladeComments\Http\Middleware\AddRequestComments is registered in app/Http/Kernel.php (it is by default).
    • Exclusions: Check excludes.includes and excludes.sections to avoid cluttering partials or meta tags.

Implementation Patterns

Core Workflows

  1. Debugging Blade Renders:

    • Inspect Hierarchy: Use the top-level comment (e.g., <!-- BEGIN: resources/views/home.blade.php -->) to identify the root view.
    • Trace Components: Livewire/Blade components (e.g., @component('widget.card')) are auto-detected and commented.
    • Section Yields: @yield('section-name') directives are wrapped with comments, even in nested layouts.
  2. Integration with Existing Tools:

    • Browser DevTools: Right-click → "Inspect" to jump to the Blade file (VS Code/Laravel IDE Helper integration works seamlessly).
    • CI/CD: Disable in production by setting APP_DEBUG=false or overriding blade-comments.enable=false in .env.
  3. Custom Commenters:

    • Extend BladeCommenter: Add support for custom directives (e.g., @myDirective):
      namespace App\BladeComments;
      
      use Spatie\BladeComments\Commenters\BladeCommenters\BladeCommenter;
      
      class MyDirectiveCommenter implements BladeCommenter {
          public function pattern(): string { return '/@myDirective\s*(.*?)\s*/'; }
          public function replacement(): string { return '<!-- BEGIN: @myDirective $1 -->$0<!-- END: @myDirective -->'; }
      }
      
      Register in config/blade-comments.php:
      'blade_commenters' => [
          // ... default commenters
          App\BladeComments\MyDirectiveCommenter::class,
      ],
      
  4. Request Metadata:

    • Leverage RequestCommenter to inject custom data (e.g., user agent, request duration):
      namespace App\BladeComments;
      
      use Spatie\BladeComments\Commenters\RequestCommenters\RequestCommenter;
      use Illuminate\Http\Request;
      use Symfony\Component\HttpFoundation\Response;
      
      class UserAgentCommenter implements RequestCommenter {
          public function comment(Request $request, Response $response): ?string {
              return "<!-- User Agent: {$request->userAgent()} -->";
          }
      }
      
      Add to request_commenters in config.

Pro Tips

  • Performance: Comments are only added in debug mode (APP_DEBUG=true). Zero overhead in production.
  • Livewire 4+: Supports component resolution via BladeComponentCommenter (no manual setup needed).
  • Exclude Strategically: Use excludes.includes for CSS/JS partials (e.g., 'styles.main') to avoid noise.
  • AST-Based Parsing: Since v2.0, the package uses Laravel’s Blade AST parser (more reliable than regex for complex directives).

Gotchas and Tips

Pitfalls

  1. False Positives in Excludes:

    • Issue: Partial matches in excludes.includes (e.g., 'header' might exclude 'header.partial').
    • Fix: Use full paths (e.g., 'partials.header') or regex patterns in the config:
      'excludes' => [
          'includes' => [
              '/^styles\./', // Exclude all files starting with "styles."
          ],
      ],
      
  2. Conditional Includes:

    • Issue: @include('partial', ['key' => $value]) may fail if $value is undefined.
    • Fix: Ensure all included views are resolvable or use try-catch in custom commenters.
  3. Middleware Order:

    • Issue: Comments might not appear if AddRequestComments runs after the response is sent.
    • Fix: Place it before StartSession and ShareErrorsFromSession in Kernel.php:
      protected $middleware = [
          // ...
          \Spatie\BladeComments\Http\Middleware\AddRequestComments::class,
          // ...
      ];
      
  4. Livewire Component Namespaces:

    • Issue: Custom Livewire components (e.g., App\Livewire\Admin\Dashboard) may not resolve correctly.
    • Fix: Extend LivewireComponentCommenter to handle namespaced classes:
      class CustomLivewireCommenter extends \Spatie\BladeComments\Commenters\BladeCommenters\LivewireComponentCommenter {
          protected function resolveClass(string $class): ?string {
              return class_exists($class) ? $class : null;
          }
      }
      

Debugging

  • Missing Comments:

    • Verify APP_DEBUG=true in .env.
    • Check if the middleware is registered in Kernel.php.
    • Run php artisan config:clear if config changes aren’t reflected.
  • Malformed Comments:

    • Ensure Blade files are not minified (comments won’t render in minified output).
    • Use php artisan view:clear to regenerate cached views.

Extension Points

  1. Dynamic Exclusions:

    • Override excludes via a service provider:
      public function boot() {
          config(['blade-comments.excludes.includes' => array_merge(
              config('blade-comments.excludes.includes'),
              ['dynamic.partial']
          )]);
      }
      
  2. Conditional Commenting:

    • Disable comments for specific routes:
      Route::middleware(['web', 'blade-comments:disable'])->group(function () {
          // Comments will be skipped here
      });
      
      Add this middleware to Kernel.php:
      protected $routeMiddleware = [
          'blade-comments.disable' => \Spatie\BladeComments\Http\Middleware\DisableBladeComments::class,
      ];
      
  3. Custom Comment Formatting:

    • Modify the comment template by extending BladeCommentsPrecompiler:
      class CustomPrecompiler extends \Spatie\BladeComments\BladeCommentsPrecompiler {
          protected function wrapWithComments(string $content, string $path): string {
              return "<!-- CUSTOM: $path -->$content<!-- /CUSTOM -->";
          }
      }
      
      Update the config:
      'precompiler' => App\BladeComments\CustomPrecompiler::class,
      

Performance Quirks

  • Large Views: Comments add negligible overhead (~1ms per view in debug mode). Monitor with:
    php artisan debugbar:enable
    
  • Caching: Blade comments are not cached in production (disabled by APP_DEBUG). No impact on view:cache.
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.
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
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai