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

Mixpanel Php Laravel Package

mixpanel/mixpanel-php

Official Mixpanel PHP library for tracking events and updating user profiles. Send server-side analytics data (events, people, groups) to Mixpanel using a simple API, with support for batching, async transport options, and configurable endpoints.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require mixpanel/mixpanel-php
    

    Add the service provider and facade to config/app.php:

    'providers' => [
        // ...
        Mixpanel\Mixpanel::class,
    ],
    'aliases' => [
        // ...
        'Mixpanel' => Mixpanel\Facades\Mixpanel::class,
    ],
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Mixpanel\MixpanelServiceProvider"
    

    Update .env with your Mixpanel API token:

    MIXPANEL_TOKEN=your_api_token_here
    
  3. First Event Track a user's first action (e.g., login):

    use Mixpanel\Facades\Mixpanel;
    
    $userId = 'user123';
    $properties = [
        '$first_name' => 'John',
        '$email' => 'john@example.com',
        'plan' => 'premium',
    ];
    
    Mixpanel::track($userId, 'Login', $properties);
    
  4. Verify in Mixpanel Check the Events tab in your Mixpanel dashboard for the Login event.


Where to Look First

  • Official Docs (limited but covers core methods).
  • Config File (config/mixpanel.php): Adjust timeout, proxy, or batch settings.
  • Facade Methods: track(), identify(), people_set(), people_increment() (see API Reference).

Implementation Patterns

Core Workflows

1. Tracking User Actions

// Track a custom event (e.g., "Checkout Started")
Mixpanel::track('user123', 'Checkout Started', [
    'items' => 3,
    'value' => 99.99,
    'device' => 'mobile',
]);

2. User Identification & Properties

// Set core user traits (runs `$identify`)
Mixpanel::identify('user123', [
    '$first_name' => 'Jane',
    '$email' => 'jane@example.com',
    'account_created' => '2023-01-01',
]);

// Update a single property (e.g., plan upgrade)
Mixpanel::people_set('user123', 'plan', 'enterprise');

3. People Analytics (Metrics)

// Increment a numeric property (e.g., "lifetime_value")
Mixpanel::people_increment('user123', 'lifetime_value', 50.00);

// Append to a list (e.g., "purchased_items")
Mixpanel::people_append('user123', 'purchased_items', 'product_456');

4. Batch Processing

Enable batching in config/mixpanel.php:

'batch' => [
    'enabled' => true,
    'max_events' => 100,
    'flush_interval' => 60, // seconds
],
  • Useful for high-volume apps (e.g., SaaS platforms).
  • Events are queued and sent in bulk.

Integration Tips

Laravel-Specific Patterns

  • Middleware for Auto-Tracking Attach to kernel.php to track requests:

    Mixpanel::track('user123', 'Page View', [
        'page' => request()->path(),
        'referrer' => request()->header('referer'),
    ]);
    
  • Event Service Providers Dispatch events (e.g., UserRegistered) and track them:

    event(new UserRegistered($user));
    // In listener:
    Mixpanel::track($user->id, 'User Registered', ['source' => 'email']);
    
  • Queue Workers for Async Tracking Offload tracking to a queue (e.g., trackEvent job):

    dispatch(new TrackEventJob($userId, 'Video Watched', $properties));
    

Common Use Cases

Use Case Example Code
Feature Flags Mixpanel::track('user123', 'Feature:Dark Mode', ['enabled' => true])
A/B Testing Mixpanel::track('user123', 'Experiment:Navbar', ['variant' => 'B'])
Error Tracking Mixpanel::track('user123', 'Error:Checkout', ['error' => $e->getMessage()])

Gotchas and Tips

Pitfalls

  1. Rate Limits

    • Mixpanel’s API has rate limits (1000 requests/minute).
    • Fix: Use batching or queue events during traffic spikes.
  2. Duplicate Events

    • Accidental duplicate track() calls (e.g., in middleware + controller).
    • Fix: Add a guard:
      if (!Mixpanel::hasTracked($userId, 'Login', $properties)) {
          Mixpanel::track($userId, 'Login', $properties);
      }
      
  3. Property Size Limits

    • Events > 15KB or properties > 100KB are rejected.
    • Fix: Serialize complex data (e.g., json_encode()).
  4. Async Delays

    • Batching introduces latency (events may take flush_interval seconds to appear).
    • Fix: Use Mixpanel::flush() to force-sync critical events.

Debugging

  • Enable Debug Mode
    Mixpanel::setDebug(true); // Logs requests to `storage/logs/mixpanel.log`
    
  • Check Response Codes Wrap calls in a try-catch:
    try {
        Mixpanel::track($userId, 'Event');
    } catch (\Exception $e) {
        Log::error("Mixpanel error: " . $e->getMessage());
    }
    
  • Validate Properties Mixpanel rejects malformed data (e.g., unescaped quotes). Use:
    $properties = json_decode(json_encode($properties), true);
    

Extension Points

  1. Custom HTTP Client Override the default Guzzle client in MixpanelServiceProvider:

    $this->app->singleton('mixpanel.client', function () {
        return new \GuzzleHttp\Client(['timeout' => 30]);
    });
    
  2. Event Transformers Pre-process events before sending:

    Mixpanel::extend(function ($tracker) {
        $tracker->beforeTrack(function ($event) {
            $event['properties']['env'] = app()->environment();
        });
    });
    
  3. Webhook Fallback For critical events, duplicate to a webhook:

    $response = Mixpanel::track($userId, 'Payment Success', $properties);
    if (!$response->success()) {
        Http::post('https://your-fallback-webhook.com', $properties);
    }
    

Config Quirks

  • Timeouts: Default is 5 seconds. Increase for unstable networks:
    'timeout' => 10,
    
  • Proxy Support: Configure if behind a firewall:
    'proxy' => [
        'http'  => 'http://proxy.example.com:8080',
        'https' => 'http://proxy.example.com:8080',
    ],
    
  • SSL Verification: Disable only for testing:
    'verify_ssl' => false,
    
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.
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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