Installation Add the package via Composer:
composer require assoconnect/rudderstack-bundle
Register the bundle in config/app.php under providers:
Assoconnect\RudderstackBundle\RudderstackServiceProvider::class,
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
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);
}
Verify Integration Check RudderStack dashboard or destination (e.g., Google Analytics, Mixpanel) for the event.
track() for custom events:
$rudderstack->track([
'event' => 'PageView',
'properties' => ['pageUrl' => '/home'],
]);
$rudderstack->identify([
'userId' => 'user123',
'traits' => ['email' => '[email protected]', 'name' => 'John Doe'],
]);
For high-throughput scenarios, batch events:
$events = [
['event' => 'Event1', 'properties' => [...]],
['event' => 'Event2', 'properties' => [...]],
];
$rudderstack->trackBatch($events);
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',
],
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,
];
Use Laravel’s request() helper or service containers to dynamically populate properties:
$rudderstack->track([
'event' => 'CheckoutStarted',
'properties' => [
'cartValue' => $request->cartValue,
'userAgent' => $request->userAgent(),
],
]);
Skip tracking for specific routes/users:
if (auth()->check() && !auth()->user()->isAdmin()) {
$rudderstack->track($event);
}
Extend the bundle to support custom destinations (e.g., internal APIs):
$rudderstack->sendToCustomDestination([
'destination' => 'my_custom_dest',
'payload' => $event,
]);
Mock RudderStack in tests:
$this->partialMock(Rudderstack::class, function ($mock) {
$mock->shouldReceive('track')->once();
});
Environment Variables
RUDDERSTACK_DATA_PLANE_URL and RUDDERSTACK_WRITE_KEY are never committed to version control..env.example as a template for shared environments.Queue Delays
php artisan queue:work
Payload Size Limits
properties.url to offload data to a CDN or external service.Rate Limiting
try {
$rudderstack->track($event);
} catch (\Assoconnect\RudderstackBundle\Exceptions\RateLimitExceeded $e) {
sleep(2); // Retry after delay
$rudderstack->track($event);
}
Debugging
config/rudderstack.php:
'debug' => env('APP_DEBUG', false),
storage/logs/laravel.log.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);
Type Safety Cast properties to expected types to avoid serialization issues:
$event['properties']['price'] = (float) $request->price;
Performance
tap() to chain operations:
$event = tap($event, function ($e) {
$e['properties']['timestamp'] = now()->toIso8601String();
});
$rudderstack->track($event);
Environment-Specific Config
Override config per environment (e.g., config/rudderstack-local.php):
'write_key' => env('RUDDERSTACK_WRITE_KEY_LOCAL'),
Monitoring
failed queue job:
$rudderstack->track($event)->catch(function ($e) {
\Log::error("RudderStack failed: " . $e->getMessage());
});
Extending the Bundle
Rudderstack service binding in a service provider:
$this->app->bind(Rudderstack::class, function ($app) {
return new \Assoconnect\RudderstackBundle\Services\CustomRudderstack(
$app['config']['rudderstack']
);
});
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()],
]);
How can I help you explore Laravel packages today?