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

Analytics Laravel Package

thujohn/analytics

Laravel 4 package providing a simple facade/service to query the Google Analytics Core Reporting API. Configure your GA credentials, get a site ID by URL, and fetch metrics like visits and pageviews over custom date ranges.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require thujohn/analytics
    

    Add the service provider to config/app.php:

    'providers' => [
        // ...
        Thujohn\Analytics\AnalyticsServiceProvider::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Thujohn\Analytics\AnalyticsServiceProvider"
    

    Update config/analytics.php with your Google Analytics Tracking ID (e.g., UA-XXXXXX-X).

  3. First Use Case Track a page view in a controller or blade template:

    use Thujohn\Analytics\Facades\Analytics;
    
    // Track a page view
    Analytics::trackPageView('/dashboard');
    
    // Or in Blade:
    @analytics->trackPageView('/user/profile');
    

Implementation Patterns

Core Workflows

  1. Tracking Events Log custom events (e.g., button clicks, form submissions):

    Analytics::trackEvent('User', 'Signed Up', 'Dashboard');
    
  2. E-Commerce Tracking Track transactions and product views:

    Analytics::trackTransaction('12345', 99.99, 'USD');
    Analytics::trackProductView('P123', 'Product Name', 19.99);
    
  3. Middleware Integration Auto-track routes via middleware:

    namespace App\Http\Middleware;
    
    use Thujohn\Analytics\Facades\Analytics;
    use Closure;
    
    class TrackPageViews
    {
        public function handle($request, Closure $next)
        {
            Analytics::trackPageView($request->path());
            return $next($request);
        }
    }
    

    Register in app/Http/Kernel.php:

    protected $middleware = [
        // ...
        \App\Http\Middleware\TrackPageViews::class,
    ];
    
  4. Blade Directives Use @analytics directives for quick tracking:

    @analytics->trackEvent('User', 'Clicked', 'CTA Button')
    
  5. Queueing Events Offload tracking to a queue (requires queue config):

    Analytics::trackEvent('User', 'Action', 'Data', true); // 4th param = queue
    

Gotchas and Tips

Pitfalls

  1. Tracking ID Validation

    • Ensure config/analytics.php has a valid tracking_id (e.g., UA-XXXXXX-X).
    • Empty or malformed IDs will silently fail. Test with:
      if (!Analytics::isConfigured()) {
          throw new \RuntimeException('Analytics not configured!');
      }
      
  2. Queue Configuration

    • If using queued events, ensure analytics.queue is set to true in config and the analytics queue exists:
      php artisan queue:work --queue=analytics
      
    • Unprocessed queued events may delay reporting.
  3. HTTPS/Protocol Issues

    • The package defaults to https://www.google-analytics.com. If your app uses a custom domain (e.g., analytics.yourdomain.com), override the URL in config:
      'url' => 'https://analytics.yourdomain.com/collect',
      
  4. Debugging

    • Enable debug mode in config to log payloads:
      'debug' => env('APP_DEBUG', false),
      
    • Check Laravel logs for failed requests (e.g., network errors).
  5. Rate Limiting

    • Google Analytics has quota limits. Avoid excessive real-time tracking in loops.

Tips

  1. Environment-Specific Tracking Disable tracking in local environments:

    if (app()->environment('local')) {
        Analytics::disable();
    }
    
  2. Custom Dimensions Extend tracking with custom dimensions (requires GA setup):

    Analytics::setCustomDimension(1, 'User Role', auth()->user()->role);
    
  3. Batch Processing For high-traffic apps, batch events to reduce API calls:

    Analytics::flush(); // Force send pending events
    
  4. Testing Use the Analytics::shouldTrack() method to conditionally disable tracking:

    if (Analytics::shouldTrack()) {
        Analytics::trackEvent('Test', 'Event');
    }
    
  5. Fallback for GA Outages Implement a fallback (e.g., log to a database) if GA is unreachable:

    Analytics::setFallback(function ($payload) {
        \Log::info('GA Fallback:', $payload);
    });
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport