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

Mousetracker Laravel Package

benmacha/mousetracker

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require benmacha/mousetracker dev-master
    
    • Note: The package is outdated (last release in 2017) and lacks Laravel-specific support, so adapt Symfony patterns to Laravel.
  2. Laravel Integration:

    • Manually register the bundle-like functionality in AppServiceProvider:
      public function boot()
      {
          $this->app->singleton('mouseTracker', function ($app) {
              return new \benmacha\mousetracker\Tracker();
          });
      }
      
  3. First Use Case:

    • Inject the tracker into a Blade view or controller to log mouse movements:
      use benmacha\mousetracker\Tracker;
      
      public function index(Tracker $tracker)
      {
          $tracker->startTracking(); // Initialize tracking
          return view('home');
      }
      
    • Add JavaScript to your Blade template (adapted from Symfony example):
      <script>
          Mousetracker.init({
              token: '{{ config("mousetracker.token") }}',
              callback: '{{ route("mousetracker.callback") }}'
          });
      </script>
      

Implementation Patterns

Usage Patterns

  1. Tracking Initialization:

    • Start tracking in a controller or middleware before rendering the view:
      public function show(Tracker $tracker)
      {
          $tracker->startTracking($userId, $pageUrl);
          return view('page');
      }
      
  2. Event-Based Tracking:

    • Use Laravel events to trigger tracking on specific actions (e.g., form submissions):
      Event::listen('form.submitted', function ($event) {
          app('mouseTracker')->logEvent('form_submit', $event->data);
      });
      
  3. Middleware Integration:

    • Create middleware to auto-start tracking for all routes:
      public function handle($request, Closure $next)
      {
          app('mouseTracker')->startTracking($request->user()->id, $request->url());
          return $next($request);
      }
      
  4. Blade Directives:

    • Extend Blade with custom directives for tracking:
      Blade::directive('track', function ($expression) {
          return "<?php app('mouseTracker')->logEvent('{$expression}'); ?>";
      });
      
      Usage:
      @track('button_click')
      

Workflows

  1. User-Specific Tracking:

    • Pass user IDs to correlate mouse movements with user accounts:
      $tracker->startTracking(auth()->id(), request()->fullUrl());
      
  2. A/B Testing:

    • Log variations of page elements (e.g., button colors) to analyze engagement:
      $tracker->logEvent('button_color', ['variant' => 'red']);
      
  3. Heatmaps:

    • Combine with frontend libraries (e.g., Heatmap.js) to visualize data collected via mousetracker.

Integration Tips

  • Frontend Setup:

    • Include the MouseTracker JavaScript library in your resources/js/app.js:
      window.Mousetracker = {
          init: function(config) {
              // Adapted from original library
              const script = document.createElement('script');
              script.src = `https://tracker.example.com/track?token=${config.token}`;
              script.onload = () => {
                  fetch(config.callback, {
                      method: 'POST',
                      body: JSON.stringify({ event: 'page_view' })
                  });
              };
              document.body.appendChild(script);
          }
      };
      
    • Call Mousetracker.init() in your main app entry point.
  • Backend Logging:

    • Store raw data in a database table (e.g., mouse_events) with columns:
      Schema::create('mouse_events', function (Blueprint $table) {
          $table->id();
          $table->unsignedBigInteger('user_id')->nullable();
          $table->string('event_type');
          $table->json('metadata');
          $table->timestamps();
      });
      
  • Laravel Queues:

    • Offload event processing to a queue for performance:
      $tracker->logEvent('click', ['element' => 'cta_button'])
          ->dispatch();
      

Gotchas and Tips

Pitfalls

  1. Outdated Package:

    • The package is abandoned (last release in 2017) and lacks Laravel compatibility. Expect:
      • Deprecated Symfony dependencies (e.g., Symfony\Component\HttpKernel).
      • No PHP 8+ support.
    • Workaround: Fork the repo and adapt it to Laravel’s ecosystem (e.g., replace Symfony services with Laravel’s container).
  2. No Built-in Database Support:

    • The package assumes you’ll handle storage. Use Laravel’s Eloquent or a queue system to persist data.
  3. JavaScript Dependency:

    • The original library is not included; you must implement the frontend tracking logic manually (see Integration Tips).
  4. Token Management:

    • The package expects a token for authentication. Store it securely in .env:
      MOUSETRACKER_TOKEN=your_secure_token_here
      
  5. Performance Overhead:

    • Tracking mouse movements generates high-volume data. Use:
      • Database indexing on user_id and event_type.
      • Laravel’s shouldQueue() to batch inserts.

Debugging

  1. Verify Tracking:

    • Check browser console for network requests to your callback endpoint:
      console.log('Tracking initiated:', Mousetracker);
      
    • Inspect Laravel logs for processed events:
      tail -f storage/logs/laravel.log | grep mouse_tracker
      
  2. Common Issues:

    • 404 Errors: Ensure your callback route is defined:
      Route::post('/tracker/callback', [TrackerController::class, 'callback']);
      
    • CORS Issues: If using AJAX, configure CORS in App\Http\Middleware\HandleCors:
      $this->allowMethods(['POST']);
      $this->allowCredentials();
      $this->allowOrigins(['https://yourdomain.com']);
      
  3. Data Validation:

    • Sanitize user-provided metadata to prevent SQL injection:
      $metadata = json_decode($request->input('metadata'), true);
      $tracker->logEvent('custom', array_filter($metadata));
      

Config Quirks

  1. Manual Configuration:

    • Since the package lacks Laravel config files, define settings in config/mousetracker.php:
      return [
          'token' => env('MOUSETRACKER_TOKEN'),
          'callback_url' => route('mousetracker.callback'),
          'events_whitelist' => ['click', 'hover', 'scroll'],
      ];
      
  2. Environment-Specific Tokens:

    • Use .env variables for different environments:
      MOUSETRACKER_TOKEN_LOCAL=local_token
      MOUSETRACKER_TOKEN_PROD=prod_token
      

Extension Points

  1. Custom Event Types:

    • Extend the tracker to support domain-specific events:
      class CustomTracker extends \benmacha\mousetracker\Tracker
      {
          public function logCheckoutStep($step, $data)
          {
              $this->logEvent('checkout_step', [
                  'step' => $step,
                  'data' => $data,
                  'timestamp' => now()
              ]);
          }
      }
      
  2. Data Transformation:

    • Override the logEvent method to transform data before storage:
      $tracker->setTransformer(function ($event, $metadata) {
          return [
              'event' => strtolower($event),
              'metadata' => array_merge($metadata, ['processed_at' => now()])
          ];
      });
      
  3. Third-Party Integrations:

    • Pipe data to analytics tools (e.g., Google Analytics, Mixpanel):
      Event::listen('mouse.tracked', function ($event) {
          \Analytics::track($event->userId, $event->eventType, $event->metadata);
      });
      
  4. Real-Time Processing:

    • Use Laravel Echo/Pusher to broadcast mouse events to admin dashboards:
      broadcast(new MouseEvent($event->userId, $event->eventType, $event->metadata));
      
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.
emuniq/filament-browser-notifications
syriable/filament-translator
hungnm28/livewire-form
wenprise/eloquent
crudly/encrypted
fadion/bouncy
cuci/prototurk-sdk
gos/pubsub-router-bundle
cuci/prototurk-sdk-symfony
clementtalleu/easyadmin-markdown-bundle
codeflextech/permission-manager
karnoweb/livewire-datepicker
sayedenam/sayed-dashboard
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui