Weave 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

Rudderstack Bundle Laravel Package

assoconnect/rudderstack-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the package via Composer:

    composer require assoconnect/rudderstack-bundle
    

    Register the bundle in config/app.php under providers:

    Assoconnect\RudderstackBundle\RudderstackServiceProvider::class,
    
  2. Configuration Publish the config file:

    php artisan vendor:publish --provider="Assoconnect\RudderstackBundle\RudderstackServiceProvider" --tag="rudderstack-config"
    

    Update .env with your RudderStack Data Plane URL and Write Key:

    RUDDERSTACK_DATA_PLANE_URL=https://your-data-plane-url.rudderstack.com
    RUDDERSTACK_WRITE_KEY=your_write_key_here
    
  3. First Use Case: Track an Event Inject the Rudderstack service into a controller or service:

    use Assoconnect\RudderstackBundle\Services\Rudderstack;
    
    public function trackEvent(Request $request, Rudderstack $rudderstack)
    {
        $event = [
            'userId' => 'user123',
            'event' => 'Purchase',
            'properties' => [
                'amount' => 99.99,
                'productId' => 'prod_456',
            ],
        ];
    
        $rudderstack->track($event);
    }
    
  4. Verify Integration Check RudderStack dashboard or destination (e.g., Google Analytics, Mixpanel) for the event.


Implementation Patterns

Core Workflows

1. Event Tracking

  • Standard Events: Use track() for custom events:
    $rudderstack->track([
        'event' => 'PageView',
        'properties' => ['pageUrl' => '/home'],
    ]);
    
  • User Identification: Attach user context:
    $rudderstack->identify([
        'userId' => 'user123',
        'traits' => ['email' => '[email protected]', 'name' => 'John Doe'],
    ]);
    

2. Batch Processing

For high-throughput scenarios, batch events:

$events = [
    ['event' => 'Event1', 'properties' => [...]],
    ['event' => 'Event2', 'properties' => [...]],
];
$rudderstack->trackBatch($events);

3. Integration with Laravel Queues

Offload RudderStack calls to a queue (e.g., trackLater):

$rudderstack->trackLater($event); // Dispatches to queue

Configure queue in config/rudderstack.php:

'queue' => [
    'enabled' => true,
    'connection' => 'redis',
],

4. Middleware for Automatic Tracking

Auto-track requests (e.g., page views) via middleware:

namespace App\Http\Middleware;

use Assoconnect\RudderstackBundle\Services\Rudderstack;
use Closure;

class TrackPageViews
{
    public function __construct(protected Rudderstack $rudderstack) {}

    public function handle($request, Closure $next)
    {
        $this->rudderstack->track([
            'event' => 'PageView',
            'properties' => ['path' => $request->path()],
        ]);
        return $next($request);
    }
}

Register in app/Http/Kernel.php:

protected $middleware = [
    \App\Http\Middleware\TrackPageViews::class,
];

Advanced Patterns

1. Dynamic Event Properties

Use Laravel’s request() helper or service containers to dynamically populate properties:

$rudderstack->track([
    'event' => 'CheckoutStarted',
    'properties' => [
        'cartValue' => $request->cartValue,
        'userAgent' => $request->userAgent(),
    ],
]);

2. Conditional Tracking

Skip tracking for specific routes/users:

if (auth()->check() && !auth()->user()->isAdmin()) {
    $rudderstack->track($event);
}

3. Custom Destinations

Extend the bundle to support custom destinations (e.g., internal APIs):

$rudderstack->sendToCustomDestination([
    'destination' => 'my_custom_dest',
    'payload' => $event,
]);

4. Testing

Mock RudderStack in tests:

$this->partialMock(Rudderstack::class, function ($mock) {
    $mock->shouldReceive('track')->once();
});

Gotchas and Tips

Pitfalls

  1. Environment Variables

    • Ensure RUDDERSTACK_DATA_PLANE_URL and RUDDERSTACK_WRITE_KEY are never committed to version control.
    • Use .env.example as a template for shared environments.
  2. Queue Delays

    • If using queues, events may not appear in RudderStack immediately. Monitor queue workers:
      php artisan queue:work
      
  3. Payload Size Limits

    • RudderStack has a 150KB payload limit. Avoid sending large arrays or files directly.
    • For large properties, use properties.url to offload data to a CDN or external service.
  4. Rate Limiting

    • Exceeding RudderStack’s rate limits (e.g., >1000 events/sec) may cause drops. Implement exponential backoff:
      try {
          $rudderstack->track($event);
      } catch (\Assoconnect\RudderstackBundle\Exceptions\RateLimitExceeded $e) {
          sleep(2); // Retry after delay
          $rudderstack->track($event);
      }
      
  5. Debugging

    • Enable debug mode in config/rudderstack.php:
      'debug' => env('APP_DEBUG', false),
      
    • Logs will appear in storage/logs/laravel.log.

Tips

  1. Event Schema Validation Use Laravel’s validation to enforce event structure before sending:

    $validated = $request->validate([
        'event' => 'required|string|max:255',
        'properties.userId' => 'sometimes|string',
    ]);
    $rudderstack->track($validated);
    
  2. Type Safety Cast properties to expected types to avoid serialization issues:

    $event['properties']['price'] = (float) $request->price;
    
  3. Performance

    • Batch events where possible to reduce HTTP calls.
    • Use Laravel’s tap() to chain operations:
      $event = tap($event, function ($e) {
          $e['properties']['timestamp'] = now()->toIso8601String();
      });
      $rudderstack->track($event);
      
  4. Environment-Specific Config Override config per environment (e.g., config/rudderstack-local.php):

    'write_key' => env('RUDDERSTACK_WRITE_KEY_LOCAL'),
    
  5. Monitoring

    • Track failed events with Laravel’s failed queue job:
      $rudderstack->track($event)->catch(function ($e) {
          \Log::error("RudderStack failed: " . $e->getMessage());
      });
      
    • Use RudderStack’s Debugger to inspect real-time events.
  6. Extending the Bundle

    • Override the Rudderstack service binding in a service provider:
      $this->app->bind(Rudderstack::class, function ($app) {
          return new \Assoconnect\RudderstackBundle\Services\CustomRudderstack(
              $app['config']['rudderstack']
          );
      });
      
  7. Webhooks for Server-Side Events For server-side events (e.g., cron jobs), use the track method directly without middleware:

    $rudderstack->track([
        'event' => 'DailySummary',
        'properties' => ['metrics' => $this->generateMetrics()],
    ]);
    
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.
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console
pnscripts/filament-broadquill-lite
pnscripts/laravel-sentfold-lite
vleap/mx-sdk-laravel-internal
twidpay/utils
htetmyathlaing/scout-elasticsearch-driver
artisan-toolbox/front-awesome
ls/client-assistant
users-au/laravel-client
robertmarney/lara-hierarchial-collections
simonschaufi/rule-doc-generator
emissaoja/emissaoja
blackbricksoftware/gravityforms-civicrm-form-processor
al-rahabi/fancy-crud
jinas/dhivatar-component
mltstephane/laravel-quality
bernskiold/laravel-talentlms
bernskioldmedia/laravel-form-architect