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 Google Analytics Laravel Package

bezhansalleh/filament-google-analytics

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require bezhansalleh/filament-google-analytics
    

    Publish the config file:

    php artisan vendor:publish --provider="BezhanSalleh\FilamentGoogleAnalytics\FilamentGoogleAnalyticsServiceProvider" --tag="filament-google-analytics-config"
    
  2. Configuration Edit .env or config/filament-google-analytics.php:

    FILAMENT_GOOGLE_ANALYTICS_VIEW_ID=GA4_MEASUREMENT_ID
    FILAMENT_GOOGLE_ANALYTICS_TRACKING_ID=UA-XXXXXX-Y
    

    For GA4, use the Measurement ID (e.g., G-XXXXXXXXXX). For Universal Analytics, use the Tracking ID (e.g., UA-XXXXXX-Y).

  3. Enable in Filament Panel Add to your PanelProvider (e.g., app/Providers/Filament/AdminPanelProvider.php):

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->default()
            ->id('admin')
            ->googleAnalytics();
    }
    
  4. First Use Case Immediately start tracking admin panel usage. No additional code needed—just refresh your Filament dashboard.


Implementation Patterns

Core Workflows

  1. Tracking Page Views Automatically logs:

    • Page titles (e.g., /admin/resources/posts)
    • User IDs (if authenticated)
    • Session duration
    • Device/OS info (via browser headers)
  2. Custom Events Manually trigger events for critical actions:

    use BezhanSalleh\FilamentGoogleAnalytics\Facades\FilamentGoogleAnalytics;
    
    FilamentGoogleAnalytics::trackEvent(
        title: 'Post Published',
        category: 'Content',
        action: 'Publish',
        label: 'Post ID: 123',
        value: 1
    );
    

    Best Practice: Use in:

    • Resource controllers (e.g., store(), update())
    • Custom actions (e.g., bulk deletes)
    • Widget interactions
  3. Integration with Filament Features

    • Resources: Track CRUD actions via resource hooks:

      public static function getPages(): array
      {
          return [
              'index' => Pages\ListPosts::route('/'),
              'create' => Pages\CreatePost::route('/create'),
              'edit' => Pages\EditPost::route('/{record}/edit'),
          ];
      }
      

      The package auto-detects these routes for tracking.

    • Widgets: Log dashboard widget usage:

      FilamentGoogleAnalytics::trackScreen('Dashboard', 'StatsWidget');
      
  4. Multi-Panel Support Configure separate tracking IDs for different Filament panels:

    ->panel()
        ->id('admin')
        ->googleAnalytics(viewId: 'GA4_ADMIN_ID')
        ->panel()
        ->id('tenant')
        ->googleAnalytics(viewId: 'GA4_TENANT_ID')
    

Advanced Patterns

  1. Dynamic Tracking IDs Use environment variables or database-driven config:

    config([
        'filament-google-analytics.view_id' => env('FILAMENT_GA_VIEW_ID', fn() => DB::table('settings')->value('ga_view_id')),
    ]);
    
  2. Excluding Pages Opt out specific routes (e.g., login pages):

    FilamentGoogleAnalytics::ignoreRoutes(['/admin/auth/login']);
    
  3. Custom Dimensions Pass user metadata (e.g., roles, subscriptions):

    FilamentGoogleAnalytics::setUserProperties([
        'user_id' => auth()->id(),
        'role' => auth()->user()->role,
    ]);
    
  4. Server-Side Event Validation Validate events before sending (e.g., in a middleware):

    public function handle(Request $request, Closure $next)
    {
        if (!FilamentGoogleAnalytics::isValidEvent($request->input())) {
            abort(403);
        }
        return $next($request);
    }
    

Gotchas and Tips

Common Pitfalls

  1. GA4 vs. Universal Analytics

    • GA4: Use viewId (e.g., G-XXXXXXXXXX).
    • Universal: Use trackingId (e.g., UA-XXXXXX-Y).
    • Mixed Config: Only one can be set at a time. Clear unused fields in config.
  2. CORS/HTTPS Issues

    • Ensure your Filament app uses HTTPS (Google Analytics blocks HTTP requests).
    • If using a proxy (e.g., Nginx), forward headers:
      proxy_set_header X-Forwarded-Proto $scheme;
      
  3. Rate Limiting

    • Google Analytics has a quota (~200k hits/day).
    • Tip: Batch events or use FilamentGoogleAnalytics::flush() manually in high-traffic areas.
  4. Debugging

    • Enable debug mode in config:
      'debug' => env('FILAMENT_GA_DEBUG', false),
      
    • Check logs for failed requests:
      tail -f storage/logs/laravel.log | grep "GoogleAnalytics"
      
  5. Filament Widget Conflicts

    • If using filament/spatie-laravel-analytics, disable its auto-tracking to avoid duplicates:
      Spatie\Analytics\Analytics::ignoreRoutes(['/admin/*']);
      

Pro Tips

  1. Segmentation Use custom dimensions to segment data by:

    • User roles (user_role)
    • Tenant IDs (tenant_id)
    • Feature flags (feature_x_enabled)
  2. Performance Optimization

    • Disable tracking for non-critical pages (e.g., API routes):
      FilamentGoogleAnalytics::disable();
      
    • Lazy-load the tracker:
      if (app()->environment('production')) {
          FilamentGoogleAnalytics::enable();
      }
      
  3. Testing

  4. Extension Points

    • Custom Tracker: Implement BezhanSalleh\FilamentGoogleAnalytics\Contracts\Tracker for alternative providers (e.g., Matomo).
    • Event Filters: Extend FilamentGoogleAnalyticsServiceProvider to modify events:
      public function boot()
      {
          FilamentGoogleAnalytics::macro('logSensitiveData', function ($event) {
              if (Str::contains($event['label'], 'password')) {
                  return false;
              }
              return true;
          });
      }
      
  5. Data Retention

    • GA4 auto-deletes data after 2/3 months. For long-term storage, export to BigQuery or use a local database:
      FilamentGoogleAnalytics::setLogger(new DatabaseLogger());
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware