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.
- 🚀 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
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
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.
The simplest way to track elements is using data attributes:
<button data-sonar="signup-button" data-sonar-metadata='{"variant": "blue"}'>
Sign Up
</button>
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>
);
}
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>;
}
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
]);
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
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,
],
// ...
];
You can configure the JavaScript behavior globally:
import { configureSonar } from "laravel-sonar";
configureSonar({
trackAllHovers: true, // Enable tracking of repeated hovers
});
Laravel Sonar provides several methods to analyze your collected data. You can use these methods to build dashboards or generate reports.
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();
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.
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');
});
}
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
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(),
]);
}
}
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
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
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
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...
The MIT License (MIT). Please see License File for more information.