PHPackages                             mafrasil/laravel-sonar - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mafrasil/laravel-sonar

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mafrasil/laravel-sonar
======================

Product analytics

v0.1.7(1y ago)111[4 PRs](https://github.com/mafrasil/laravel-sonar/pulls)MITPHPPHP ^8.3CI passing

Since Feb 3Pushed 2mo ago1 watchersCompare

[ Source](https://github.com/mafrasil/laravel-sonar)[ Packagist](https://packagist.org/packages/mafrasil/laravel-sonar)[ Docs](https://github.com/mafrasil/laravel-sonar)[ GitHub Sponsors](https://github.com/mafrasil)[ RSS](/packages/mafrasil-laravel-sonar/feed)WikiDiscussions main Synced today

READMEChangelog (5)Dependencies (13)Versions (14)Used By (0)

Laravel Sonar - Product Analytics
=================================

[](#laravel-sonar---product-analytics)

[![Latest Version on Packagist](https://camo.githubusercontent.com/a67c1017f445df09455d8e9ad3dd787f94f100cb28943590108753c60ad56d19/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d6166726173696c2f6c61726176656c2d736f6e61722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mafrasil/laravel-sonar)[![GitHub Tests Action Status](https://camo.githubusercontent.com/08f3275823e2dda4afddb6c35c10817cfd5e9dd6dafba4d512370d40dbb3d830/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f6d6166726173696c2f6c61726176656c2d736f6e61722f72756e2d74657374732e796d6c3f6272616e63683d6d61696e266c6162656c3d7465737473267374796c653d666c61742d737175617265)](https://github.com/mafrasil/laravel-sonar/actions?query=workflow%3Arun-tests+branch%3Amain)[![Total Downloads](https://camo.githubusercontent.com/fb71d738596dcdb1d6b8f827a1282528a4d394d4513effd52c84341399a39f3b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d6166726173696c2f6c61726176656c2d736f6e61722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mafrasil/laravel-sonar)

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

[](#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
------------

[](#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

[](#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
-----

[](#usage)

### Data Attributes

[](#data-attributes)

The simplest way to track elements is using data attributes:

```

    Sign Up

```

### React Component (Optional)

[](#react-component-optional)

If you've exported the React components, you can use the `SonarTracker` component:

```
import { SonarTracker } from "@/components/SonarTracker";

function SignupButton() {
    return (

            Sign Up

    );
}
```

### Custom Events

[](#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 fields */};
}
```

### Server-Side Tracking

[](#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
-----------

[](#event-types)

The package supports the following event types out of the box:

- `click`: User clicks on tracked elements
- `hover`: User hovers over tracked elements (configurable for repeated tracking)
- `impression`: Element becomes visible in the viewport
- `custom`: Any custom event you want to track

Configuration
-------------

[](#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

[](#javascript-configuration)

You can configure the JavaScript behavior globally:

```
import { configureSonar } from "laravel-sonar";

configureSonar({
    trackAllHovers: true, // Enable tracking of repeated hovers
});
```

Analytics
---------

[](#analytics)

Laravel Sonar provides several methods to analyze your collected data. You can use these methods to build dashboards or generate reports.

### Available Methods

[](#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 &amp; Analytics
-------------------------

[](#dashboard--analytics)

### CLI 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

[](#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

[](#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

[](#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

[](#available-analytics-methods)

#### Basic Analytics

[](#basic-analytics)

- `getEventsByType(DateTime $startDate = null, DateTime $endDate = null)`: Get event counts grouped by type
- `getTopLocations(int $limit = 10, DateTime $startDate = null)`: Get most active pages/routes
- `getEventTimeline(string $interval = '1 day', DateTime $startDate = null)`: Get event distribution over time
- `getTopEvents(int $limit = 10, string $type = null)`: Get most triggered events
- `getUserEngagement()`: Get overall engagement metrics

#### Detailed Analytics

[](#detailed-analytics)

- `getElementStats(int $limit = 10)`: Get element-specific stats with conversion rates
- `getBrowserStats()`: Get browser and device usage statistics
- `getScreenSizeStats()`: Get screen size distribution
- `getMetadataStats(string $name)`: Get detailed metadata analysis for specific elements
- `getLocationStats()`: Get detailed page interaction statistics

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security Vulnerabilities
------------------------

[](#security-vulnerabilities)

Please review [our security policy](../../security/policy) on how to report security vulnerabilities.

Inspiration &amp; Acknowledgments
---------------------------------

[](#inspiration--acknowledgments)

Laravel Sonar was inspired by [Pan](https://github.com/panphp/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
-------

[](#credits)

- [mafrasil](https://github.com/mafrasil)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance66

Regular maintenance activity

Popularity7

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 82.6% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

8

Last Release

479d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/133235707?v=4)[Tiago](/maintainers/mafrasil)[@mafrasil](https://github.com/mafrasil)

---

Top Contributors

[![mafrasil](https://avatars.githubusercontent.com/u/133235707?v=4)](https://github.com/mafrasil "mafrasil (38 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (4 commits)")

---

Tags

laravelmafrasillaravel-sonar

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/mafrasil-laravel-sonar/health.svg)

```
[![Health](https://phpackages.com/badges/mafrasil-laravel-sonar/health.svg)](https://phpackages.com/packages/mafrasil-laravel-sonar)
```

###  Alternatives

[spatie/laravel-pdf

Create PDFs in Laravel apps

1.0k4.8M47](/packages/spatie-laravel-pdf)[codewithdennis/filament-select-tree

The multi-level select field enables you to make single selections from a predefined list of options that are organized into multiple levels or depths.

329530.5k29](/packages/codewithdennis-filament-select-tree)[rawilk/profile-filament-plugin

Profile &amp; MFA starter kit for filament.

3914.6k](/packages/rawilk-profile-filament-plugin)[worksome/exchange

Check Exchange Rates for any currency in Laravel.

124603.0k](/packages/worksome-exchange)[tarfin-labs/event-machine

Event-driven state machines for Laravel with event sourcing, type-safe context, and full audit trail.

199.4k](/packages/tarfin-labs-event-machine)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
