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

Filament Connection Badge Laravel Package

rawand201/filament-connection-badge

Drop-in connection status badge for Filament panels. Shows live signal bars in the topbar, ping graph on hover, and optional full-screen offline overlay. Works with Filament v4/v5, matches theme/dark mode, supports RTL and translations.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the package:
    composer require rawand201/filament-connection-badge
    
  2. Publish assets (required for Alpine.js and CSS):
    php artisan filament:assets
    
  3. Verify functionality: The badge will automatically appear in the Filament topbar (default: before the user menu). No additional configuration is needed for basic usage.

First Use Case: Quick Health Monitoring

  • Scenario: You want to immediately monitor backend responsiveness in your Filament admin panel.
  • Steps:
    1. Navigate to any Filament panel.
    2. Observe the signal-bar badge in the topbar (next to the user avatar).
    3. Hover over the badge to see a tooltip with:
      • Live ping sparkline (last 30 samples).
      • Average/last ping times.
      • Packet loss percentage.
    4. Simulate an offline state by disabling network in browser dev tools to test the overlay.

Implementation Patterns

Core Workflow: Integrating into Filament

  1. Default Integration:

    • The badge renders automatically via the panels::user-menu.before hook (same as PanelsRenderHook::USER_MENU_BEFORE).
    • Custom Hook: Change the render location by setting FILAMENT_CONNECTION_BADGE_RENDER_HOOK in .env (e.g., panels::topbar.end).
  2. Ping Monitoring:

    • The package registers a /_filament-connection-badge/ping endpoint (configurable via ping_url).
    • Custom Ping Logic: Override the default JSON response by publishing the route and extending the controller:
      // app/Http/Controllers/CustomPingController.php
      public function __invoke()
      {
          return response()->json([
              'ok' => true,
              'ts' => now()->timestamp(),
              'custom_data' => ['api' => 'healthy'], // Extend payload
          ]);
      }
      
    • Update the config to point to your custom route:
      'ping_url' => '/custom-ping-endpoint',
      
  3. Permission-Gated Access:

    • Restrict the badge and ping endpoint to authenticated users with a can() check:
      'permission' => 'viewConnectionBadge', // Must match a Gate::define() call
      
    • Register the permission in a service provider:
      Gate::define('viewConnectionBadge', function ($user) {
          return $user->isAdmin(); // Example condition
      });
      
  4. Multi-Panel Support:

    • Panel-Specific Config: Use Filament’s panel configuration to enable/disable the badge per panel:
      protected static ?string $badgeEnabled = null; // Override in Panel class
      
    • Dynamic Ping URLs: Set ping_url per panel via a trait or service provider:
      // In a Panel service provider
      FilamentConnectionBadge::configureForPanel($panelClass, [
          'ping_url' => '/panel-specific-ping',
      ]);
      
  5. Localization:

    • Publish translations and extend for new languages:
      php artisan vendor:publish --tag="filament-connection-badge-translations"
      
    • Add a new language file (e.g., resources/lang/es/es.json) and merge into the published translations.

Advanced Patterns

  1. Custom Tooltip Content:

    • Publish the view and extend the tooltip partial:
      php artisan vendor:publish --tag="filament-connection-badge-views"
      
    • Modify resources/views/vendor/filament-connection-badge/tooltip.blade.php to include additional metrics or UI elements.
  2. Theming:

    • Override colors by targeting .fcb-* classes in your panel’s CSS:
      /* Example: Change offline color */
      .fcb-offline {
          --color: var(--danger-500);
      }
      
    • Publish assets for full customization:
      php artisan vendor:publish --tag="filament-connection-badge-assets"
      
  3. Offline Overlay Customization:

    • Disable the overlay globally:
      'show_overlay' => false,
      
    • Or extend the overlay view (published via --tag=filament-connection-badge-views) to add a custom message or actions.
  4. Testing:

    • Unit Test the Ping Endpoint:
      public function test_ping_endpoint()
      {
          $response = $this->getJson('/_filament-connection-badge/ping');
          $response->assertOk()->assertJsonStructure(['ok', 'ts']);
      }
      
    • Integration Test the Badge: Use Laravel’s actingAs() and browser testing to verify the badge renders and updates correctly:
      $this->actingAs(User::factory()->create())
           ->get('/filament/admin/resources')
           ->assertSee('fcb-badge');
      

Gotchas and Tips

Common Pitfalls

  1. Badge Not Appearing:

    • Cause: Assets not published.
    • Fix: Run php artisan filament:assets and clear cache (php artisan optimize:clear).
    • Debug: Check browser console for Alpine.js errors (e.g., missing window.Alpine).
  2. Ping Endpoint 404:

    • Cause: Route not registered due to enabled = false or missing middleware.
    • Fix: Verify .env:
      FILAMENT_CONNECTION_BADGE_ENABLED=true
      
    • Debug: Run php artisan route:list | grep filament-connection-badge to confirm the route exists.
  3. Permission Denied (403):

    • Cause: permission is set but the user lacks the ability.
    • Fix: Register the permission in a service provider or grant it to the user:
      $user->givePermissionTo('viewConnectionBadge'); // If using Laravel Nova permissions
      
  4. High Latency or Packet Loss:

    • Cause: Ping URL points to a slow endpoint or is blocked by middleware.
    • Fix: Use a lightweight endpoint (e.g., /favicon.ico or a dedicated ping route):
      'ping_url' => '/favicon.ico',
      
    • Debug: Test the ping URL manually in browser/dev tools to isolate the issue.
  5. Overlay Not Dismissing:

    • Cause: JavaScript errors preventing the online event listener from firing.
    • Fix: Check browser console for errors and ensure navigator.onLine is supported (it is in all modern browsers).
  6. RTL Issues:

    • Cause: Custom tooltip content may not respect RTL direction.
    • Fix: Use CSS logical properties (e.g., margin-inline-start) or wrap text in <span dir="ltr">.

Debugging Tips

  1. Log Ping Data:

    • Extend the Alpine component to log ping samples to the console:
      // resources/js/filament-connection-badge.js (published via --tag=assets)
      window.addEventListener('alpine:init', () => {
          Alpine.data('connectionBadge', () => ({
              // ... existing code ...
              pingSamples: [],
              logSamples() {
                  console.log('Ping samples:', this.pingSamples);
              },
          }));
      });
      
  2. Simulate Offline State:

    • Use Chrome DevTools (Application > Service Workers > Offline) or JavaScript:
      // Simulate offline
      window.dispatchEvent(new Event('offline'));
      // Simulate online
      window.dispatchEvent(new Event('online'));
      
  3. Inspect Network Requests:

    • Check the ping endpoint in the Network tab to verify:
      • Response time (should match the badge’s latency).
      • Headers (e.g., Cache-Control: no-store).
      • Payload structure ({ "ok": true, "ts": 12345 }).

Configuration Quirks

  1. Throttling:

    • Set FILAMENT_CONNECTION_BADGE_THROTTLE to limit ping frequency (e.g., 60,1 = 60 requests per minute).
    • Warning: Aggressive throttling may cause stale latency readings.
  2. Ping URL Security:

    • Avoid public endpoints (e.g., /ping) to prevent abuse. Use middleware like auth or throttle:
      'route' => [
          'middleware' => ['web', 'auth', 'throttle:60,1'],
      ],
      
  3. Dark Mode:

    • Colors automatically inherit from Filament’s theme (e.g., --success-500). Override via CSS if needed:
      .fcb-full {
          --color: var(--gray-800); /* Force a specific color */
      }
      
  4. Multi-Language Fallback:

    • If a translation is missing, the package falls back to English. Ensure your language files include all keys:
      {
          "connection_badge": {
              "offline": "
      
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.
directorytree/privacy-filter-classifier
directorytree/privacy-filter
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata
splash/openapi
splash/scopes
splash/toolkit
testo/output-teamcity
testo/bridge-symfony
spatie/flare-daemon-runtime