beloop/analytics
Read-only Analytics component from the Beloop LMS suite. Part of beloop/components (Symfony-based) under the MIT license. Includes Travis CI and Packagist releases; issues and PRs should be opened in the main beloop/components repo.
Installation Ensure your project meets the PHP 7.2+ requirement (BREAKING CHANGE in v1.0). Add the package via Composer:
composer require beloop/analytics
Publish the config file (if available):
php artisan vendor:publish --provider="Beloop\Analytics\AnalyticsServiceProvider"
Basic Configuration
Locate the config file at config/analytics.php and set your API keys/endpoints:
'sources' => [
'google' => [
'api_key' => env('GOOGLE_ANALYTICS_API_KEY'),
'view_id' => env('GOOGLE_ANALYTICS_VIEW_ID'),
'min_php_version' => '7.2', // Explicitly noted for compliance
],
],
First Use Case: Track a Page View
Inject the Analytics facade into a controller or service:
use Beloop\Analytics\Facades\Analytics;
public function show()
{
Analytics::trackPageView('/dashboard');
}
Event-Based Tracking Bind Laravel events to analytics tracking (PHP 7.2+ compatible):
// In EventServiceProvider
public function boot()
{
Analytics::onUserRegistered(function ($user) {
Analytics::trackEvent('User Registered', [
'user_id' => $user->id,
'email' => $user->email,
]);
});
}
Middleware for Automatic Tracking Create middleware to track page views automatically (ensure PHP 7.2+):
namespace App\Http\Middleware;
use Beloop\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,
];
Batch Processing for Efficiency
Use the flush() method to batch track events (PHP 7.2+):
Analytics::trackEvent('Product Viewed', ['product_id' => 123]);
Analytics::trackEvent('Product Viewed', ['product_id' => 456]);
Analytics::flush(); // Send all queued events at once
Laravel Mix/Inertia.js: Track frontend interactions via API endpoints (PHP 7.2+ backend):
// Frontend (e.g., Inertia.js)
window.trackEvent = (eventName, data) => {
axios.post('/api/track', { event: eventName, data });
};
Backend endpoint (ensure PHP 7.2+):
Route::post('/api/track', function (Request $request) {
Analytics::trackEvent($request->event, $request->data);
});
Queue Workers: Offload analytics tracking to a queue for performance (PHP 7.2+):
Analytics::trackEvent('Order Placed', ['order_id' => 789])->queue();
PHP Version Requirement (BREAKING CHANGE) The package now requires PHP 7.2+. Update your environment or use a legacy version:
composer require beloop/analytics:0.9.* # Fallback to pre-1.0
Deprecated API Calls The package is archived (last release: 2019). Assume undocumented breaking changes if integrating with modern Google Analytics (e.g., GA4). Verify API endpoints and payload structures against the official docs.
No Built-in Rate Limiting Without queueing, rapid calls (e.g., in loops) may hit API limits. Always batch or queue events:
// Bad: Spamming API (PHP 7.2+ but still inefficient)
foreach ($users as $user) {
Analytics::trackEvent('User Action', ['user_id' => $user->id]);
}
// Good: Batched (PHP 7.2+)
foreach ($users as $user) {
Analytics::trackEvent('User Action', ['user_id' => $user->id]);
}
Analytics::flush();
Missing Error Handling The package lacks built-in retry logic for failed requests. Wrap calls in try-catch (PHP 7.2+):
try {
Analytics::trackEvent('Critical Event', $data);
} catch (\Exception $e) {
Log::error("Analytics failed: " . $e->getMessage());
// Fallback: Log to local DB or dead-letter queue
}
Enable Logging
Add to config/analytics.php:
'debug' => env('APP_DEBUG', false),
Logs will appear in storage/logs/laravel.log.
Mock Analytics in Tests Use a mock service provider or override the facade (PHP 7.2+):
// In tests/CreatesApplication.php
$app->singleton(\Beloop\Analytics\Contracts\Analytics::class, function () {
return new class {
public function trackEvent($event, $data) {
// Assert or log for testing
}
};
});
Custom Sources
Extend support for new analytics providers by implementing Beloop\Analytics\Contracts\AnalyticsSource (PHP 7.2+):
namespace App\Analytics;
use Beloop\Analytics\Contracts\AnalyticsSource;
class MixpanelSource implements AnalyticsSource
{
public function track($event, $data)
{
// Custom Mixpanel logic (PHP 7.2+)
}
}
Register in config/analytics.php:
'sources' => [
'mixpanel' => [
'class' => \App\Analytics\MixpanelSource::class,
'token' => env('MIXPANEL_TOKEN'),
],
],
Event Transformers Modify payloads before sending via a transformer (PHP 7.2+):
Analytics::setTransformer(function ($event, $data) {
return [
'event' => strtolower($event),
'properties' => array_merge($data, ['app_version' => '1.0']),
];
});
Webhook Fallback For critical events, add a webhook fallback (PHP 7.2+):
Analytics::trackEvent('Fallback Test', ['data' => 'test'])
->fallback(function ($event, $data) {
Http::post('https://your-webhook-endpoint', [
'event' => $event,
'data' => $data,
]);
});
How can I help you explore Laravel packages today?