mafrasil / laravel-sonar
Product analytics
Fund package maintenance!
mafrasil
Requires
- php: ^8.3
- illuminate/contracts: ^10.0||^11.0||^12.0
- spatie/laravel-package-tools: ^1.16
Requires (Dev)
- larastan/larastan: ^2.9
- laravel/pint: ^1.14
- nunomaduro/collision: ^8.1.1||^7.10.0
- orchestra/testbench: ^9.0.0||^8.22.0||^10.0.0
- pestphp/pest: ^3.0
- pestphp/pest-plugin-arch: ^3.0
- pestphp/pest-plugin-laravel: ^3.0
- phpstan/extension-installer: ^1.3
- phpstan/phpstan-deprecation-rules: ^1.1
- phpstan/phpstan-phpunit: ^1.3
- spatie/laravel-ray: ^1.35
README
Laravel Sonar is a powerful product analytics package that makes it easy to track user interactions in your Laravel application. It provides automatic tracking for clicks, hovers, and impressions, with support for custom events.
Features
- 🚀 Automatic event tracking (clicks, hovers, impressions)
- 🎯 Custom event tracking
- ⚡ Efficient batch processing of events
- 🛠️ Optional React components and hooks for easy integration
- 📱 Responsive design support with screen size tracking
- 🔄 Compatible with Inertia.js
- ⚙️ Configurable tracking behavior
Installation
You can install the package via composer:
composer require mafrasil/laravel-sonar
Then install the package and publish the assets:
php artisan sonar:install php artisan vendor:publish --tag=sonar-assets
This will publish the config file, assets and run the migrations.
You can also publish the config file, assets and run the migrations separately:
php artisan vendor:publish --tag=sonar-config # Publish the config file php artisan vendor:publish --tag=sonar-assets # Publish the assets php artisan vendor:publish --tag=sonar-migrations # Publish the migrations php artisan migrate # Run the migrations
You can also publish the views of the dashboard:
php artisan vendor:publish --tag=sonar-views
Optional: Export React Components
If you're using React, you can export the React components and TypeScript types:
php artisan sonar:export-react
This will create React components and hooks in your application's JavaScript directory.
Usage
Data Attributes
The simplest way to track elements is using data attributes:
<button data-sonar="signup-button" data-sonar-metadata='{"variant": "blue"}'> Sign Up </button>
React Component (Optional)
If you've exported the React components, you can use the SonarTracker
component:
import { SonarTracker } from "@/components/SonarTracker"; function SignupButton() { return ( <SonarTracker name="signup-button" metadata={{ variant: "blue" }} trackAllHovers={true} // Optional: track repeated hovers > <button>Sign Up</button> </SonarTracker> ); }
Custom Events
Use the useSonar
hook for custom event tracking and configuration:
import { useSonar } from "@/hooks/useSonar"; function CheckoutForm() { const { track, configure } = useSonar(); // Optional: Configure tracking behavior useEffect(() => { configure({ trackAllHovers: true }); }, []); const handleSubmit = () => { track("checkout-complete", "custom", { amount: 99.99, currency: "USD", }); }; return <form onSubmit={handleSubmit}>{/* form fields */}</form>; }
Server-Side Tracking
You can also track events from your PHP code:
use Mafrasil\LaravelSonar\Facades\LaravelSonar; LaravelSonar::track('order-processed', 'custom', [ 'orderId' => $order->id, 'amount' => $order->total ]);
Event Types
The package supports the following event types out of the box:
click
: User clicks on tracked elementshover
: User hovers over tracked elements (configurable for repeated tracking)impression
: Element becomes visible in the viewportcustom
: Any custom event you want to track
Configuration
You can customize the package behavior in the config/sonar.php
file:
return [ 'route' => [ 'prefix' => 'api', 'middleware' => ['api'], ], 'queue' => [ 'batch_size' => 10, 'flush_interval' => 1000, ], // ... ];
JavaScript Configuration
You can configure the JavaScript behavior globally:
import { configureSonar } from "laravel-sonar"; configureSonar({ trackAllHovers: true, // Enable tracking of repeated hovers });
Analytics
Laravel Sonar provides several methods to analyze your collected data. You can use these methods to build dashboards or generate reports.
Available Methods
use Mafrasil\LaravelSonar\Facades\LaravelSonar; // Get events grouped by type $eventsByType = LaravelSonar::getEventsByType( startDate: now()->subDays(7), // optional endDate: now() // optional ); // Get most active pages $topPages = LaravelSonar::getTopPages( limit: 10, // optional, defaults to 10 startDate: now()->subDays(30) // optional ); // Get event timeline $timeline = LaravelSonar::getEventTimeline( interval: '1 day', // optional, defaults to '1 day' startDate: now()->subDays(30) // optional ); // Get most triggered events $topEvents = LaravelSonar::getTopEvents( limit: 10, // optional, defaults to 10 type: 'click' // optional, filter by event type ); // Get user engagement metrics $engagement = LaravelSonar::getUserEngagement();
Dashboard & Analytics
CLI Analytics
The package includes a convenient command-line interface for quick analytics overview:
php artisan sonar:stats --limit=20
This is particularly useful for quick analytics checks or automated reporting scripts.
Access Control
By default, the Sonar dashboard is only accessible in the local environment.
You can enable it anytime by setting the SONAR_DASHBOARD_ENABLED environment variable to true.
To allow specific users in other environments, configure the allowed emails in your config/sonar.php
:
'allowed_emails' => [ 'user@example.com', ],
You can also customize the authorization logic by overriding the viewSonar
gate in your AuthServiceProvider
:
use Illuminate\Support\Facades\Gate; public function boot() { Gate::define('viewSonar', function ($user) { return $user->hasRole('admin') || $user->hasPermission('view-analytics'); }); }
Dashboard Access
The dashboard is available at /sonar
and provides:
- Event type distribution
- Most active pages
- Click and hover rates
- User engagement metrics
- Browser and device statistics
- Screen size distribution
- Detailed element interaction analysis
Using the Facade
The LaravelSonar
facade provides various methods for analyzing your tracking data. Here's a comprehensive example:
class AnalyticsDashboardController extends Controller { public function index() { return view('analytics.dashboard', [ 'eventsByType' => LaravelSonar::getEventsByType(now()->subDays(30)), 'topPages' => LaravelSonar::getTopPages(5), 'dailyEvents' => LaravelSonar::getEventTimeline(), 'topClickedElements' => LaravelSonar::getTopEvents(5, 'click'), 'engagement' => LaravelSonar::getUserEngagement(), ]); } }
Available Analytics Methods
Basic Analytics
getEventsByType(DateTime $startDate = null, DateTime $endDate = null)
: Get event counts grouped by typegetTopLocations(int $limit = 10, DateTime $startDate = null)
: Get most active pages/routesgetEventTimeline(string $interval = '1 day', DateTime $startDate = null)
: Get event distribution over timegetTopEvents(int $limit = 10, string $type = null)
: Get most triggered eventsgetUserEngagement()
: Get overall engagement metrics
Detailed Analytics
getElementStats(int $limit = 10)
: Get element-specific stats with conversion ratesgetBrowserStats()
: Get browser and device usage statisticsgetScreenSizeStats()
: Get screen size distributiongetMetadataStats(string $name)
: Get detailed metadata analysis for specific elementsgetLocationStats()
: Get detailed page interaction statistics
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Inspiration & Acknowledgments
Laravel Sonar was inspired by Pan, a lightweight and privacy-focused PHP product analytics library. While sharing similar core concepts for simple analytics tracking, Laravel Sonar extends the functionality with additional features including:
- Rich metadata support for events
- Built-in analytics dashboard UI
- Advanced analytics reporting capabilities
- Screen size and device tracking
- Detailed user engagement metrics
- React component integration
- And more...
Credits
License
The MIT License (MIT). Please see License File for more information.