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 Setup

  1. Installation:

    composer require spatie/laravel-blade-comments --dev
    

    The package auto-registers and works immediately in APP_DEBUG=true environments.

  2. First Use Case:

    • Open your browser's dev tools (F12) and inspect any rendered Blade view.
    • Look for HTML comments like:
      <!-- /resources/views/layouts/app.blade.php -->
      
      These wrap the rendered output, showing the Blade file path responsible.

Where to Look First

  • Config: Publish the config (optional) for customization:

    php artisan vendor:publish --tag="blade-comments-config"
    

    Key settings:

    • enable: Toggles comments (defaults to APP_DEBUG).
    • excludes.includes: Skip specific @include directives (e.g., ['partials.sidebar']).
    • excludes.sections: Skip @yield sections (e.g., ['meta']).
  • Middleware: The package adds AddRequestComments middleware automatically. Verify it’s registered in app/Http/Kernel.php under the web middleware group.


Implementation Patterns

Daily Workflow

  1. Debugging Blade Output:

    • Inspect Elements: Use browser dev tools to trace HTML back to Blade files via comments.
    • Component Debugging: Livewire/Blade components (e.g., @component('user-card')) are auto-detected and commented.
  2. Excluding Noise:

    • Partials: Exclude CSS/JS partials from comments:
      'excludes' => [
          'includes' => ['styles.theme', 'scripts.footer'],
      ],
      
    • Sections: Skip @yield directives in meta tags:
      'excludes' => [
          'sections' => ['meta', 'title'],
      ],
      
  3. Custom Comments:

    • Blade Commenters: Extend functionality by creating a custom BladeCommenter:
      namespace App\BladeComments;
      
      use Spatie\BladeComments\Commenters\BladeCommenters\BladeCommenter;
      
      class CustomDirectiveCommenter implements BladeCommenter {
          public function pattern(): string {
              return '/@custom\(.*?\)\s*/';
          }
          public function replacement(): string {
              return '<!-- @custom directive -->$0<!-- /@custom directive -->';
          }
      }
      
      Register in config/blade-comments.php:
      'blade_commenters' => [
          // ... default commenters
          App\BladeComments\CustomDirectiveCommenter::class,
      ],
      
  4. Request Metadata:

    • Custom Request Commenters: Add request-specific info (e.g., user agent, route name) to the top of the HTML:
      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()} -->";
          }
      }
      
      Register in config:
      'request_commenters' => [
          // ... default commenters
          App\BladeComments\UserAgentCommenter::class,
      ],
      

Integration Tips

  • Livewire: Supports Livewire components (v3/v4) out of the box. Comments appear around rendered components.
  • Blade Components: Works seamlessly with Laravel’s Blade components (e.g., @component('alert')).
  • Testing: Disable comments in tests by setting APP_DEBUG=false or mocking the middleware.

Gotchas and Tips

Pitfalls

  1. Performance:

    • Debug Mode Only: The package is designed for APP_DEBUG=true. Ensure it’s disabled in production ('enable' => false).
    • Exclusions: Over-excluding can reduce debugging utility. Start broad (e.g., exclude only CSS/JS partials).
  2. Edge Cases:

    • Conditional Includes: Directives like @include_if may not work as expected on Windows. Use @include explicitly if issues arise.
    • Dynamic Paths: Avoid Blade comments in dynamically generated paths (e.g., @include($dynamicPath)). Exclude these paths in config.
  3. Middleware Order:

    • Ensure AddRequestComments runs after ShareErrorsFromSession and before VerifyCsrfToken in app/Http/Kernel.php to avoid CSRF token issues.

Debugging Tips

  1. Missing Comments:

    • Check Config: Verify 'enable' => true and APP_DEBUG=true.
    • Exclusions: Confirm excluded paths/sections aren’t blocking comments.
    • Blade Cache: Clear Blade cache:
      php artisan view:clear
      
  2. Livewire Issues:

    • For Livewire v4, ensure the package is updated (>=2.0.3). Older versions may need manual component class resolution.
  3. Custom Patterns:

    • Regex Pitfalls: When extending BladeCommenter, test patterns with preg_match to avoid infinite loops or missed matches.
    • Replacement Strings: Use $0 to preserve matched content (e.g., replacement(): string { return '<!-- $0 -->'; }).

Extension Points

  1. Precompiler:

    • Override BladeCommentsPrecompiler to customize how comments are injected (e.g., add timestamps or user context).
  2. Event Hooks:

    • Listen for blade.comments.added events to log or modify comments dynamically:
      use Spatie\BladeComments\Events\CommentsAdded;
      
      CommentsAdded::listen(function (CommentsAdded $event) {
          // Log or transform comments
      });
      
  3. Conditional Comments:

    • Use RequestCommenter to add environment-specific comments (e.g., show staging warnings):
      public function comment(Request $request, Response $response): ?string {
          return app()->environment('staging')
              ? '<!-- STAGING ENVIRONMENT -->'
              : null;
      }
      
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.
nexmo/api-specification
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
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata