Install the Package
composer require souravmsh/laravel-tracker
php artisan tracker:install
php artisan migrate
Verify Dashboard Access
Navigate to /tracker (or your configured prefix) to see the default analytics dashboard. Ensure middleware (e.g., auth) is properly set in config/tracker.php.
First Use Case: Track a Referral Append a referral code to a URL:
http://your-app.com?ref=TEST123
Check the dashboard to confirm the referral is logged.
config/tracker.php – Customize routes, middleware, and caching behavior.database/migrations/[timestamp]_create_tracker_tables.php – Review schema for custom fields.app/Http/Middleware/TrackReferrals.php – Extend or override default tracking logic./tracker – Visualize referrals, UTM parameters, and visitor data.Track a Custom Event Add a tracker to a controller method:
use SouravMsh\Tracker\Facades\Tracker;
public function checkout()
{
Tracker::track('user.checkout.attempted', [
'user_id' => auth()->id(),
'cart_value' => $this->cart->total(),
]);
}
Verify the event appears in the dashboard under "Custom Events."
Leverage the built-in TrackReferrals middleware (auto-registered on the web group) to capture:
?ref=CODE).?utm_source=google).Customize Middleware:
// app/Http/Middleware/TrackReferrals.php
public function handle($request, Closure $next)
{
$request->merge([
'tracker_referral' => $request->query('ref', null),
'tracker_utm' => $request->query('utm_*', []),
]);
return $next($request);
}
Bind Laravel events to trackers:
// EventServiceProvider.php
protected $listen = [
'Illuminate\Auth\Events\Registered' => [
'SouravMsh\Tracker\Listeners\TrackUserRegistration',
],
];
Enable IP-to-country mapping via queues:
// config/tracker.php
'geocoding' => [
'enabled' => true,
'queue' => 'tracker-geocode',
],
Trigger geocoding in a listener:
use SouravMsh\Tracker\Events\VisitorTracked;
public function handle(VisitorTracked $event)
{
if (config('tracker.geocoding.enabled')) {
Tracker::geocode($event->visitor->ip);
}
}
Offload heavy tasks (e.g., geocoding) to queues:
php artisan queue:work --queue=tracker-geocode
Format payloads consistently:
Tracker::track('api.request', [
'endpoint' => $request->path(),
'method' => $request->method(),
'duration_ms' => $duration,
], [
'user_agent' => $request->userAgent(),
]);
Extend the dashboard with custom widgets:
// app/Providers/TrackerServiceProvider.php
public function boot()
{
Tracker::extend(function ($dashboard) {
$dashboard->addWidget(new \App\Widgets\CustomMetricsWidget());
});
}
Prevent abuse via middleware:
use Illuminate\Cache\RateLimiter;
Route::middleware([
'throttle:100,1', // 100 requests/minute
'tracker.rate_limit',
])->group(...);
try-catch and log failures:
try {
$geocode = Http::get("https://api.ipgeolocation.io/ipgeo?apiKey={$key}&ip={$ip}");
Tracker::updateVisitorGeocode($visitor, $geocode->json());
} catch (\Exception $e) {
Log::error("Geocoding failed for IP {$ip}: " . $e->getMessage());
}
$payload = array_filter($data, fn($value) => !is_resource($value), ARRAY_FILTER_USE_BOTH);
Tracker::track('event', $payload);
cache:forever) may serve stale data.config/tracker.php:
'dashboard' => [
'cache_ttl' => 300, // 5 minutes
],
TrackReferrals runs after auth middleware, $request->user() may be null.app/Http/Kernel.php:
protected $middleware = [
// ...
\App\Http\Middleware\TrackReferrals::class,
\App\Http\Middleware\Authenticate::class,
];
use Illuminate\Support\Facades\Http;
$response = Http::retry(3, 100)->get("https://api.example.com/ip/{$ip}");
Inspect raw events in the trackers table:
php artisan tinker
>>> \SouravMsh\Tracker\Models\Tracker::latest()->first()->payload;
Test locally without queues:
// config/tracker.php
'geocoding' => [
'enabled' => false,
],
Monitor pending jobs:
php artisan queue:failed
php artisan queue:listen --queue=tracker-geocode
Test referral tracking manually:
php artisan route:list | grep tracker
curl "http://your-app.com?ref=TEST&utm_source=manual"
Force a cache refresh:
php artisan cache:clear
php artisan tracker:cache:clear
Create reusable trackers:
// app/Services/CustomTracker.php
use SouravMsh\Tracker\Contracts\Tracker as TrackerContract;
class CustomTracker implements TrackerContract
{
public function track($event, $payload, $metadata = [])
{
// Custom logic (e.g., validate payload, enrich metadata)
\SouravMsh\Tracker\Facades\Tracker::track($event, $payload, $metadata);
}
}
Add custom charts or tables:
// app/Providers/TrackerServiceProvider.php
public function boot()
{
Tracker::extend(function ($dashboard) {
$dashboard->addChart(new \App\Charts\ConversionFunnelChart());
});
}
Modify payloads before storage:
// config/tracker.php
'payload_transformers' => [
\App\Transformers\SanitizePayloadTransformer::class,
],
Replace the default geocoding service:
// app/Providers/TrackerServiceProvider.php
public function register()
{
$this->app->bind(
\SouravMsh\Tracker\Contracts\Geocoder::class,
\App\Services\CustomGeocoder::class
);
}
Hook into tracker events:
// EventServiceProvider.php
protected $listen = [
'SouravMsh\Tracker\Events\TrackerCreated' => [
\App\Listeners\LogTrackerToExternalService::class,
],
];
/admin/analytics vs. `/How can I help you explore Laravel packages today?