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

Laravel Tracker Laravel Package

souravmsh/laravel-tracker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the Package

    composer require souravmsh/laravel-tracker
    php artisan tracker:install
    php artisan migrate
    
  2. 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.

  3. 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.


Where to Look First

  • Config File: config/tracker.php – Customize routes, middleware, and caching behavior.
  • Migrations: database/migrations/[timestamp]_create_tracker_tables.php – Review schema for custom fields.
  • Middleware: app/Http/Middleware/TrackReferrals.php – Extend or override default tracking logic.
  • Dashboard: /tracker – Visualize referrals, UTM parameters, and visitor data.

First Practical Task

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."


Implementation Patterns

Core Workflows

1. Automated Tracking via Middleware

Leverage the built-in TrackReferrals middleware (auto-registered on the web group) to capture:

  • Referral codes (?ref=CODE).
  • UTM parameters (?utm_source=google).
  • IP-based geolocation (async via queues).

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);
}

2. Event-Driven Tracking

Bind Laravel events to trackers:

// EventServiceProvider.php
protected $listen = [
    'Illuminate\Auth\Events\Registered' => [
        'SouravMsh\Tracker\Listeners\TrackUserRegistration',
    ],
];

3. Asynchronous Geocoding

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);
    }
}

Integration Tips

With Laravel Queues

Offload heavy tasks (e.g., geocoding) to queues:

php artisan queue:work --queue=tracker-geocode

With Custom Payloads

Format payloads consistently:

Tracker::track('api.request', [
    'endpoint' => $request->path(),
    'method' => $request->method(),
    'duration_ms' => $duration,
], [
    'user_agent' => $request->userAgent(),
]);

With Dashboard Widgets

Extend the dashboard with custom widgets:

// app/Providers/TrackerServiceProvider.php
public function boot()
{
    Tracker::extend(function ($dashboard) {
        $dashboard->addWidget(new \App\Widgets\CustomMetricsWidget());
    });
}

With Rate Limiting

Prevent abuse via middleware:

use Illuminate\Cache\RateLimiter;

Route::middleware([
    'throttle:100,1', // 100 requests/minute
    'tracker.rate_limit',
])->group(...);

Gotchas and Tips

Pitfalls

1. Queue Worker Crashes

  • Issue: Unhandled exceptions in queue jobs (e.g., geocoding API failures) can silently drop events.
  • Fix: Wrap job logic in 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());
    }
    

2. Payload Size Limits

  • Issue: Large payloads (e.g., nested arrays) may fail to serialize or bloat the database.
  • Fix: Sanitize payloads before tracking:
    $payload = array_filter($data, fn($value) => !is_resource($value), ARRAY_FILTER_USE_BOTH);
    Tracker::track('event', $payload);
    

3. Dashboard Caching Conflicts

  • Issue: Aggressive caching (e.g., cache:forever) may serve stale data.
  • Fix: Set a reasonable TTL (e.g., 5 minutes) in config/tracker.php:
    'dashboard' => [
        'cache_ttl' => 300, // 5 minutes
    ],
    

4. Middleware Order Matters

  • Issue: If TrackReferrals runs after auth middleware, $request->user() may be null.
  • Fix: Reorder middleware in app/Http/Kernel.php:
    protected $middleware = [
        // ...
        \App\Http\Middleware\TrackReferrals::class,
        \App\Http\Middleware\Authenticate::class,
    ];
    

5. Geocoding API Throttling

  • Issue: Free geocoding APIs (e.g., ipgeolocation.io) have request limits.
  • Fix: Implement retries with exponential backoff:
    use Illuminate\Support\Facades\Http;
    
    $response = Http::retry(3, 100)->get("https://api.example.com/ip/{$ip}");
    

Debugging Tips

1. Log Raw Tracker Data

Inspect raw events in the trackers table:

php artisan tinker
>>> \SouravMsh\Tracker\Models\Tracker::latest()->first()->payload;

2. Disable Queue Workers Temporarily

Test locally without queues:

// config/tracker.php
'geocoding' => [
    'enabled' => false,
],

3. Check Queue Jobs

Monitor pending jobs:

php artisan queue:failed
php artisan queue:listen --queue=tracker-geocode

4. Validate Middleware

Test referral tracking manually:

php artisan route:list | grep tracker
curl "http://your-app.com?ref=TEST&utm_source=manual"

5. Clear Dashboard Cache

Force a cache refresh:

php artisan cache:clear
php artisan tracker:cache:clear

Extension Points

1. Custom Trackers

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);
    }
}

2. Dashboard Extensions

Add custom charts or tables:

// app/Providers/TrackerServiceProvider.php
public function boot()
{
    Tracker::extend(function ($dashboard) {
        $dashboard->addChart(new \App\Charts\ConversionFunnelChart());
    });
}

3. Payload Transformers

Modify payloads before storage:

// config/tracker.php
'payload_transformers' => [
    \App\Transformers\SanitizePayloadTransformer::class,
],

4. Custom Geocoding

Replace the default geocoding service:

// app/Providers/TrackerServiceProvider.php
public function register()
{
    $this->app->bind(
        \SouravMsh\Tracker\Contracts\Geocoder::class,
        \App\Services\CustomGeocoder::class
    );
}

5. Event Listeners

Hook into tracker events:

// EventServiceProvider.php
protected $listen = [
    'SouravMsh\Tracker\Events\TrackerCreated' => [
        \App\Listeners\LogTrackerToExternalService::class,
    ],
];

Configuration Quirks

1. Route Prefix Collisions

  • Issue: Custom prefix conflicts with existing routes (e.g., /admin/analytics vs. `/
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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