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

artisanpack-ui/analytics

Laravel package adding an admin UI for analytics: configure tracking, view key metrics and reports, and manage dashboards from your application. Designed to integrate quickly with common Laravel stacks and provide a clean, configurable analytics panel.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require artisanpack-ui/analytics artisanpack-ui/ai
    php artisan vendor:publish --provider="ArtisanPack\Analytics\AnalyticsServiceProvider" --tag="analytics-config"
    php artisan vendor:publish --provider="ArtisanPack\AI\AIServiceProvider" --tag="ai-config"
    php artisan migrate
    
    • Verify the analytics and analytics_digest_preferences tables exist in your database.
  2. Configuration

    • Open config/analytics.php and set:
      • default_driver (e.g., database or google_analytics).
      • consent_required (boolean for GDPR compliance).
      • Optional: API keys for Google Analytics 4/Plausible.
    • Enable AI features in config/ai.php:
      'features' => [
          'analytics.insight_summary' => env('FEATURE_ANALYTICS_INSIGHTS', true),
          'analytics.explain_anomaly' => env('FEATURE_ANALYTICS_ANOMALIES', true),
          'analytics.segment_insight' => env('FEATURE_ANALYTICS_SEGMENTS', true),
          'analytics.digest_email' => env('FEATURE_ANALYTICS_DIGESTS', true),
      ],
      
  3. First Use Case: Track a Page View

    use ArtisanPack\Analytics\Facades\Analytics;
    
    Analytics::track('page_view', [
        'path' => request()->path(),
        'user_id' => auth()->id(),
    ]);
    
    • Check the analytics table or dashboard for the event.
  4. First AI Use Case: Insight Summary

    use ArtisanPack\AI\Facades\AI;
    
    $summary = AI::agent('analytics.insight_summary')->run([
        'start_date' => '2024-01-01',
        'end_date' => '2024-01-31',
    ]);
    
    • Outputs structured insights like:
      {
        "summary": "Traffic increased by 15% MoM, driven by organic search.",
        "highlights": ["New blog series boosted sessions by 20%"],
        "concerns": ["Bounce rate rose on product pages"]
      }
      
    
    

Implementation Patterns

Core Workflows

  1. Event Tracking (Unchanged)

    • Page Views: Auto-track via middleware (see below).
    • Custom Events:
      Analytics::track('product_view', [
          'product_id' => $product->id,
          'price' => $product->price,
      ]);
      
  2. Middleware for Auto-Tracking Add to app/Http/Kernel.php:

    \ArtisanPack\Analytics\Http\Middleware\TrackPageViews::class,
    
  3. Consent Management (Unchanged)

    if (Analytics::consentGranted()) {
        Analytics::track('consented_event');
    }
    
  4. Multi-Tenant Support (Unchanged)

    Analytics::setTenantId($tenant->id);
    
  5. AI-Powered Insights

    • Trigger Agents Programmatically:
      // Insight summary for a date range
      $insights = AI::agent('analytics.insight_summary')->run(['start_date' => '2024-01-01']);
      
      // Explain an anomaly (e.g., traffic spike)
      $explanation = AI::agent('analytics.explain_anomaly')->run([
          'event' => 'page_view',
          'date' => '2024-01-15',
          'value' => 5000, // unexpected spike
      ]);
      
    • Livewire Integration:
      <livewire:artisanpack-analytics::ai.insight-summary
          start-date="2024-01-01"
          end-date="2024-01-31" />
      
    • React/Vue Integration:
      // React example
      const { data: insights } = useAiAgent('analytics.insight_summary', {
          start_date: '2024-01-01',
          end_date: '2024-01-31'
      });
      
  6. Digest Emails

    • Subscribe Users:
      use ArtisanPack\Analytics\Models\AnalyticsDigestPreference;
      
      $user->preference()->updateOrCreate([
          'cadence' => 'weekly', // 'off', 'weekly', or 'monthly'
      ]);
      
    • Dispatch Digests (via cron):
      php artisan analytics:digests:dispatch
      
    • Customize Email Template: Publish and extend resources/views/vendor/artisanpack-analytics/emails/digest.blade.php.

Integration Tips

  • Laravel Scout: Sync analytics data to search engines for advanced filtering.
  • Queues: Offload tracking to a queue for high-traffic sites:
    Analytics::track('event')->dispatch();
    
  • APIs: Expose endpoints for server-side tracking:
    Route::post('/api/track', [AnalyticsController::class, 'track']);
    
  • AI API Endpoints: Use the new /api/analytics/ai/* routes:
    Route::get('/api/analytics/ai/insights', [AnalyticsAIController::class, 'getInsights']);
    
    • Gate access via analytics.ai.use ability (override in AuthServiceProvider).

Gotchas and Tips

Pitfalls

  1. Database Bloat (Unchanged)

    • Configure retention in config/analytics.php:
      'retention_days' => 365,
      
    • Run php artisan analytics:prune manually or via cron.
  2. Consent Logic Errors (Unchanged)

    • Use Analytics::shouldTrack() before tracking.
  3. AI Feature Gating

    • Issue: AI features returning null or disabled states.
    • Fix: Verify feature toggles in config/ai.php and check the FeatureRegistry:
      if (AI::featureEnabled('analytics.insight_summary')) {
          $insights = AI::agent('analytics.insight_summary')->run(...);
      }
      
    • For Livewire/React/Vue, disabled states are handled automatically.
  4. Digest Email Misconfiguration

    • Issue: Digests not sending or using wrong template.
    • Fix:
      • Ensure analytics.digest_email is enabled in config/ai.php.
      • Publish the email template:
        php artisan vendor:publish --provider="ArtisanPack\Analytics\AnalyticsServiceProvider" --tag="analytics-views"
        
      • Verify the SendDigestEmailJob is queued by checking jobs table after running analytics:digests:dispatch.
  5. Laravel 13 Support

    • No Action Required: The package now supports Laravel 11/12/13. Update your composer.json constraints if needed:
      "require": {
          "illuminate/support": "^11.0|^12.0|^13.0"
      }
      

Debugging

  • Log Events (Unchanged):
    Analytics::track('debug_event', [], true); // $forceLog = true
    
  • AI Agent Debugging:
    • Enable verbose logging in config/ai.php:
      'debug' => env('AI_DEBUG', false),
      
    • Check storage/logs/laravel.log for agent prompts/responses.
  • Digest Dispatch Issues:
    • Verify the analytics_digest_preferences table has records:
      SELECT * FROM analytics_digest_preferences WHERE cadence != 'off';
      
    • Manually trigger a digest for testing:
      php artisan analytics:digests:dispatch --user=1
      
  • API Gateway Errors:
    • Ensure the analytics.ai.use ability is granted to users:
      // In AuthServiceProvider
      Gate::define('analytics.ai.use', function ($user) {
          return $user->isAdmin(); // Customize as needed
      });
      

Extension Points

  1. Custom Drivers (Unchanged) Extend \ArtisanPack\Analytics\Contracts\AnalyticsDriver.

  2. Event Modifiers (Unchanged) Listen to analytics.tracking event.

  3. Dashboard Widgets (Unchanged) Extend \ArtisanPack\Analytics\Widgets\Widget.

  4. AI Agent Customization

    • Extend Agents: Create custom agents by extending \ArtisanPack\AI\Contracts\Agent:
      class CustomAnalyticsAgent implements Agent {
          public function run(array $payload): array { ... }
      }
      
      Register in `
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.
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor