mafrasil/laravel-sonar
Composer 安装命令:
composer require mafrasil/laravel-sonar
包简介
Product analytics
README 文档
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.
mafrasil/laravel-sonar 适用场景与选型建议
mafrasil/laravel-sonar 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 11 次下载、GitHub Stars 达 1, 最近一次更新时间为 2025 年 02 月 03 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「laravel」 「mafrasil」 「laravel-sonar」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 mafrasil/laravel-sonar 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 mafrasil/laravel-sonar 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 mafrasil/laravel-sonar 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Alfabank REST API integration
Laravel Cashier integration for Polar.sh subscription billing services
Laravel package for Accurate Online API integration.
Shared RCX Laravel DataTables UI and configuration helpers.
Boot a Laravel project on any machine with one command: app:serve installs missing tools (PHP, Node, Composer, Herd, Docker), creates .env, sets up the database, runs migrations, builds assets, starts a queue worker and serves via Herd, Sail or artisan serve; app:down cleanly stops everything it sta
Branded, diagnostic error pages (500, 403, 404, 419, 503) for Filament — native Filament UI, dark mode and translations out of the box.
统计信息
- 总下载量: 11
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 1
- 点击次数: 12
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2025-02-03