Looking to hire Laravel developers? Try LaraJobs

laravel-insights maintained by nishtman

Description
A reusable Laravel analytics integration package for multiple websites and providers.
Last update
2026/11/29 10:57 (dev-main)
License
Downloads
0

Comments
comments powered by Disqus

Laravel Insights

Laravel Insights is a reusable Laravel package for configuring and storing analytics from multiple websites, Microsoft Clarity instances, and PostHog instances.

Phase 3 adds Microsoft Clarity Data Export API collection, and Phase 4 adds PostHog Query API/HogQL collection, normalization, and persistence. The package does not provide application controllers, routes, dashboards, or frontend reporting.

Installation

composer require nishtman/laravel-insights

Laravel auto-discovery registers Nishtman\LaravelInsights\LaravelInsightsServiceProvider.

Publish configuration when application-level customization is needed:

php artisan vendor:publish --tag=laravel-insights-config

The package migrations are loaded automatically by Laravel's migration system. Installation does not change the host database. Run them only when the host application is ready:

php artisan migrate

If the host application prefers copied migrations, they can be published instead:

php artisan vendor:publish --tag=laravel-insights-migrations

Do not run both the package-loaded and copied versions of the same migrations in one application.

Configuration

The package configuration remains server-side. Credentials are read from environment variables and are not exposed by the package's database models or any frontend-oriented output.

Project and provider-instance identifiers are stable application-defined keys. They map to database records through insights_websites.key and the (provider, identifier) pair on insights_provider_instances.

'projects' => [
    'website_1' => [
        'enabled' => true,
        'url' => env('LARAVEL_INSIGHTS_WEBSITE_1_URL'),
        'timezone' => env('LARAVEL_INSIGHTS_WEBSITE_1_TIMEZONE'),

        'clarity' => [
            'main' => [
                'enabled' => true,
                'token' => env('LARAVEL_INSIGHTS_CLARITY_WEBSITE_1_MAIN_TOKEN'),
                'host' => env('LARAVEL_INSIGHTS_CLARITY_WEBSITE_1_MAIN_HOST'),
                'endpoints' => [
                    'project_live_insights' => env('LARAVEL_INSIGHTS_CLARITY_WEBSITE_1_MAIN_ENDPOINT'),
                ],
                'request' => [
                    'timeout' => env('LARAVEL_INSIGHTS_CLARITY_WEBSITE_1_MAIN_TIMEOUT', 30),
                    'connect_timeout' => env('LARAVEL_INSIGHTS_CLARITY_WEBSITE_1_MAIN_CONNECT_TIMEOUT', 10),
                ],
            ],
        ],

        'posthog' => [
            'main' => [
                'enabled' => true,
                'project_id' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_PROJECT_ID'),
                'token' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_TOKEN'),
                'host' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_HOST', 'https://us.posthog.com'),
                // Optional override when the project URL differs from properties.$host.
                'website_host' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_WEBSITE_HOST'),
                'request' => [
                    'timeout' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_TIMEOUT', 30),
                    'connect_timeout' => env('LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_CONNECT_TIMEOUT', 10),
                ],
                'endpoints' => [
                    'query' => env(
                        'LARAVEL_INSIGHTS_POSTHOG_WEBSITE_1_MAIN_QUERY_ENDPOINT',
                        '/api/projects/{project_id}/query',
                    ),
                ],
                'query' => [
                    'name' => 'website-1-event-counts',
                    'sql' => 'SELECT event, count() AS event_count FROM events GROUP BY event ORDER BY event_count DESC LIMIT 1000',
                ],
            ],
        ],
    ],
],

Any number of website keys and Clarity or PostHog instance keys may be added. Provider tokens remain configuration-only and are never stored in the database.

Package-level Clarity defaults are configured under providers.clarity:

'providers' => [
    'clarity' => [
        'host' => env('LARAVEL_INSIGHTS_CLARITY_HOST', 'https://www.clarity.ms'),
        'endpoints' => [
            'project_live_insights' => env(
                'LARAVEL_INSIGHTS_CLARITY_PROJECT_LIVE_INSIGHTS_ENDPOINT',
                '/export-data/api/v1/project-live-insights',
            ),
        ],
        'request' => [
            'timeout' => env('LARAVEL_INSIGHTS_CLARITY_TIMEOUT', 30),
            'connect_timeout' => env('LARAVEL_INSIGHTS_CLARITY_CONNECT_TIMEOUT', 10),
        ],
    ],
],

An individual instance may override host, endpoints, and request settings. Clarity authentication uses Authorization: Bearer <token>.

PostHog defaults are configured under providers.posthog. The default host is the US region; use https://eu.posthog.com for an EU project or the configured self-hosted domain. The Query API endpoint is /api/projects/{project_id}/query.

PostHog private analytics queries require a Personal API Key (phx_...) with the query:read scope, or another PostHog credential explicitly permitted to use the Query API. A project token (phc_...) is intended for public event ingestion and is not sufficient for this private query integration. The token is sent only as Authorization: Bearer <token> and is never persisted or included in package exception messages.

Clarity collection API

The package exposes no routes or controllers. Host applications can use the manager from their own application services or controllers:

use Nishtman\LaravelInsights\InsightsManager;
use Nishtman\LaravelInsights\Providers\Clarity\Http\ClarityRequest;

$clarity = app(InsightsManager::class)
    ->website('website_1')
    ->clarity('main');

$result = $clarity->collect(new ClarityRequest(1, ['URL']));

$pages = $clarity
    ->pages()
    ->dateRange($from, $to)
    ->sortBy('pageviews', 'desc')
    ->limit(20)
    ->get();

$behavior = $clarity
    ->behavioral()
    ->whereDimension('breakdown', 'os=Android')
    ->get();

InsightsManager::website() and WebsiteAnalytics::clarity() select configured identifiers. The first selection creates or updates the non-secret website/provider-instance records needed by the package. Query results are Eloquent collections for advanced use, but ordinary consumers do not need to access models to build queries.

Available query methods are metrics(), pages(), behavioral(), and providerMetrics(). They support dateRange(), whereDimension(), sortBy(), limit(), get(), and first() as appropriate. pages() returns common metric records linked to stored pages. behavioral() returns Clarity-specific extension metrics such as rage clicks, dead clicks, excessive scroll, quickback clicks, and script/error clicks.

Clarity request and response rules

ClarityRequest validates the documented numOfDays values 1, 2, or 3 and the supported dimensions: Browser, Device, Country/Region, OS, Source, Medium, Campaign, Channel, and URL. No more than three dimensions may be sent, and no unsupported parameters are added.

The client uses Laravel's HTTP client, configurable timeout values, the configured endpoint, and Bearer authentication. HTTP 401, 403, 429, network failures, invalid JSON, and invalid response structures become package exceptions without including the token in their messages.

Clarity's response is a list of metric groups containing metricName and information rows. The normalizer converts numeric fields into common metric keys, canonicalizes URL dimensions without query strings or fragments, and stores Clarity-only behavioral metrics in insights_clarity_metrics. Invalid numeric values are rejected rather than changed to zero.

Response dimension keys are matched case-insensitively, so URL, Url, and other capitalization variants resolve to the requested URL dimension. Null, empty, or absent requested dimensions are represented as empty components in the normalized dimension key; they are not converted to the strings null, undefined, or unknown, and they do not invalidate an otherwise valid metric row.

The implementation makes one API request per collect() call. It does not loop over dimensions or paginate. It records request metadata and skips an identical successful request already made for the same provider instance on the current UTC day. It also refuses to send a request after ten requests have been recorded for that provider instance on the current UTC day.

PostHog collection API

PostHog collection uses the documented Query API endpoint with a HogQLQuery request. The public package API is intentionally small:

use Nishtman\LaravelInsights\InsightsManager;

$result = app(InsightsManager::class)
    ->website('website_1')
    ->posthog('main')
    ->collect();

The host application may provide a bounded, configured query when a different event breakdown is required:

use Nishtman\LaravelInsights\Providers\PostHog\Http\PostHogRequest;

$result = app(InsightsManager::class)
    ->website('website_1')
    ->posthog('main')
    ->collect(new PostHogRequest(
        'SELECT event, count() AS event_count FROM events GROUP BY event ORDER BY event_count DESC LIMIT 1000',
        'event-counts',
    ));

The default query is a one-day rolling collection query. Collection stores the configured period window, collection timestamp, query hash, and synchronization status; it is not a reporting/date-filter API. A successful identical query is skipped for the same provider instance on the same UTC day, and the default query is bounded to 1,000 rows. Failed queries are recorded as failed synchronization runs and are never treated as empty results.

The normalized PostHog metrics are:

Metric Meaning
event_count Count returned by the query for an event/dimension row. count() and event_count aliases are supported.
pageviews A derived metric for a row whose event is exactly $pageview; it has the same count as that row.
unique_users A distinct-user metric only when the query explicitly returns a supported alias such as unique_users; the package does not infer it from event counts.

Non-metric query columns become dimensions. The normalizer recognizes event, event_name, $current_url/current_url/url, host, browser, os, and device_type (with canonical keys such as event, url, host, browser, os, and device). Null, empty, and missing values remain empty dimension components; the package does not invent unknown or null values. PostHog-specific query metadata is stored in insights_posthog_metrics, while common metrics are stored in insights_metric_records.

PostHog Query API rate limits, personal-key read budgets, query cost, and project permissions remain provider-controlled. The package does not retry or fan out across dimensions automatically. See the PostHog API documentation, Query API/HogQL documentation, and API scopes when selecting a token and query.

Built-in PostHog presets

Common queries are available without writing HogQL:

$analytics = app(InsightsManager::class)
    ->website('website_1')
    ->posthog('main');

$available = $analytics->presets()->all();
$result = $analytics->preset('most_visited_pages')->collect();
$rows = $result->rows();

The built-in preset IDs are overall_traffic, new_returning_visitors, most_visited_pages, and utm_performance. Each definition exposes a stable id, name, description, fields, and limitations. Preset execution uses the same Query API client, synchronization records, normalizer, common metric persistence, provider-specific persistence, and idempotency as custom PostHogRequest collection.

Preset host filtering uses projects.<website>.url and extracts its hostname. If that differs from the host stored in PostHog, set website_host on the PostHog provider instance. The host is safely encoded as a HogQL string literal; it is not concatenated from an unescaped request value. The configured PostHog API host remains separate from the website event host.

Preset queries use the configured one-day collection window by default and bounded limits of 50 or fewer rows where applicable. New/returning classification is based on the first retained pageview in PostHog history, so PostHog retention limits can make the classification incomplete for older visitors. These presets are collection helpers, not a date-filtering or reporting engine.

Preset collect() calls are collection operations: results are normalized and stored in the existing metric tables with query-hash and snapshot metadata. A repeated same-day call skips the API request but returns rows reconstructed from the stored PostHog extension records. Empty valid results complete without creating metric records. The package returns a PostHogPresetResult; host applications do not need to parse the raw PostHog response.

Clarity snapshot limitations

Clarity exports the previous 1–3 days as a rolling window and returns data in UTC. The package stores period_start, period_end, collected_at, granularity = rolling, and observation_window_days. It does not treat a rolling snapshot as an exact calendar day and does not sum overlapping snapshots.

The additional observation_window_days migration is a compatibility change to the Phase 2 metric tables. The record_hash includes this value, so a one-day and three-day snapshot cannot accidentally be treated as the same record.

See the official Clarity Data Export API documentation for the provider contract and quotas.

Database architecture

All package tables use the insights_ prefix to reduce collisions with host application tables.

Table Purpose
insights_websites Stable website records and website-level status/timezone.
insights_provider_instances Provider type and instance identifier for each website.
insights_pages Website-scoped canonical pages, titles, and URL hashes.
insights_metric_records Provider-independent time-series metrics and dimensions.
insights_sync_runs Future synchronization history, requested/collected ranges, counters, retries, and errors.
insights_clarity_metrics Clarity-only metrics that do not fit the common schema.
insights_posthog_metrics PostHog-only metrics and query metadata that do not fit the common schema.

The common storage path is:

Website -> ProviderInstance -> MetricRecord
Website -> Page -----------> MetricRecord
ProviderInstance ----------> SyncRun
ProviderInstance ----------> ClarityMetric / PostHogMetric

MetricRecord stores a metric key such as pageviews, unique_visitors, sessions, new_visitors, returning_visitors, engagement_time, or bounce_rate. Its dimension_type and dimension_key support traffic sources, browsers, devices, geographic values, behavioral metrics, and future dimensions without a migration for every metric. Page metrics additionally use page_id and scope_key.

The record stores period_start, period_end, granularity, observation_window_days, and collected_at separately. This preserves the difference between the period represented by a provider response and the time that response was collected. Clarity rolling snapshots use granularity = rolling and record the requested window size. The host application or provider normalizer is responsible for timezone presentation; Clarity responses are stored using UTC boundaries.

Pages store the canonical URL as text and a fixed-length url_hash for uniqueness. URL normalization is intentionally not performed by the package in this phase; future collectors should normalize query strings according to the host application's chosen policy before creating a page record.

Idempotency

Normalized records use a deterministic record_hash and a unique constraint on (provider_instance_id, record_hash). This prevents a repeated collection of the same normalized metric period from creating duplicates while allowing the same metric identity to exist for different provider instances.

The package registers Nishtman\LaravelInsights\Support\RecordIdentity, which produces the hash from the metric, dimension, scope, granularity, period boundaries, and optional observation window. Provider-specific metric tables use the same idempotency strategy.

Provider-specific storage

The common table is the intended source for future package reporting. Clarity and PostHog tables are separate extension points for metrics or metadata that cannot be represented usefully as common records. They reference insights_provider_instances, so provider-specific data remains associated with both its website and its configured provider instance without placing provider-specific columns in the common table.

Raw provider responses are not stored in Phase 2. This avoids making raw payload retention mandatory and avoids accidentally persisting credentials or authentication headers. A future opt-in raw-response table can be added independently if troubleshooting or reprocessing requires it.

Database compatibility

The migrations use Laravel's schema abstraction, portable strings, decimals, timestamps, text fields, foreign keys, and fixed-length hashes. They do not use JSON querying, enums, generated columns, vendor-specific SQL, or database-specific indexes.

Long page URLs remain in text columns and are indexed through fixed-length hashes. External dimension keys, labels, provider hosts, and external identifiers use 1024-character unindexed columns; their idempotency constraints continue to use fixed-length hashes rather than long composite indexes. This avoids utf8mb4 index-length problems on MariaDB 10.3 while supporting percent-encoded and multilingual dimension values. The package does not change the host database charset, collation, or server configuration.

The forward migration 2026_01_01_000010_widen_insights_external_values updates existing installations. The original migrations use the widened definitions for fresh installations.

Intended future workflow

Future collection components are expected to:

  1. Resolve a configured website and provider instance.
  2. Create a SyncRun for the requested period.
  3. Fetch provider data and normalize common metrics into MetricRecord values.
  4. Persist provider-specific values in the relevant extension table when needed.
  5. Use deterministic record identities to make retries idempotent.
  6. Complete the SyncRun with collected ranges, counters, timestamps, and errors.

Clarity collection is implemented in Phase 3 and PostHog collection in Phase 4. Scheduling, reporting, and dashboard implementation remain outside this package.