Looking to hire Laravel developers? Try LaraJobs

laravel-traffic maintained by etienne-scherrer

Author
Etienne Scherrer
Last update
2026/12/03 10:49 (1.0.0)
License
Downloads
0

Comments
comments powered by Disqus

laravel-traffic

Cookie-free visitor statistics for Laravel apps: page views and unique visitors per host, page and day, plus an optional Filament page that shows them.

Requirements

  • PHP 8.5
  • Laravel 13
  • Redis, or another persistent cache store (see Cache store)
  • Filament 5, optional, only for the statistics page

What it counts and what it stores

A middleware on the web group counts a request after the response has been sent, when all of these hold:

  • the method is GET, the status is 200 and the response is text/html
  • nobody is signed in on the default guard (a resolved user, the guard's session key or its "remember me" cookie)
  • the User-Agent is not a bot, crawler, uptime probe or HTTP library
  • the path is not in traffic.excluded_paths and no Traffic::excludeWhen() callback claims it

A visitor is a SHA-256 hash of a random daily salt, the IP address and the User-Agent. The salt changes every day in the configured timezone and expires after 50 hours, so a hash cannot be traced back to an IP and the same person is a new visitor the next day. A visitor is unique per host per day.

The database holds only daily totals: traffic_days (views and visitors per host and day) and traffic_pages (views and visitors per host, page and day). Totals are kept indefinitely.

Never stored: cookies (none are set), IP addresses, user agents, referrers, query strings, or the value of a route parameter listed in traffic.secret_parameters (such a route is stored as its pattern, for example /share/{token}). A counting failure is reported to the exception handler and never reaches the visitor.

Install

composer require etienne-scherrer/laravel-traffic
php artisan migrate

The service provider is auto-discovered and starts counting right away. The migrations create traffic_days and traffic_pages, and leave existing tables of the same name in place.

Cache store

The daily salt and the "seen" keys that make a visitor unique live in a cache store, not in the database. They must survive php artisan optimize:clear, which every deploy runs and which flushes the default cache store, or that day's visitors are counted twice.

By default the provider registers a Redis connection traffic (a copy of your default Redis connection on database TRAFFIC_REDIS_DB) and a cache store traffic on it, unless your app already defines either. Without Redis, point TRAFFIC_CACHE_STORE at another persistent store that is not your default one, for example a database or file store of its own.

Environment

Variable Default Purpose
TRAFFIC_ENABLED true Turns counting on or off. Read once at boot, so changing traffic.enabled at runtime has no effect
TRAFFIC_CACHE_STORE traffic Cache store holding the daily salt and the seen keys
TRAFFIC_REDIS_DB 2 Redis database of the traffic connection

The package's own test suite runs on in-memory SQLite. To run it against a real database, set TRAFFIC_TEST_DB_CONNECTION (for example mariadb), TRAFFIC_TEST_DB_HOST, TRAFFIC_TEST_DB_PORT, TRAFFIC_TEST_DB_DATABASE, TRAFFIC_TEST_DB_USERNAME and TRAFFIC_TEST_DB_PASSWORD. The suite drops every table in that database.

Configuration

Publish the config to change it:

php artisan vendor:publish --tag=traffic-config
Key Default Purpose
enabled env('TRAFFIC_ENABLED', true) Off switch
timezone 'Europe/Zurich' When a day starts
cache_store env('TRAFFIC_CACHE_STORE', 'traffic') Store for the salt and the seen keys
redis_database env('TRAFFIC_REDIS_DB', 2) Database of the traffic Redis connection
excluded_paths ['admin', 'admin/*', 'livewire*', 'horizon', 'horizon/*', 'up'] Path patterns never counted, as for $request->is()
secret_parameters ['token'] Route parameters that turn a path into its route pattern, so secret links never reach the statistics
extra_bots [] User-Agent fragments treated as bots on top of the built-in list, matched case-insensitively

Excluding requests

For anything excluded_paths cannot express, register a callback in a service provider's boot(). It receives the request and returns true to skip it. An app that signs its admins in without a guard, for example through a session flag, excludes them like this:

use EtienneScherrer\Traffic\Traffic;
use Illuminate\Http\Request;

public function boot(): void
{
    Traffic::excludeWhen(fn (Request $request): bool => $request->hasSession()
        && $request->session()->get('admin') === true);
}

Host header

The host is read from the request's Host header. Without a check on it, a client can invent hosts and each one gets rows of its own. Trust only your app's hosts in bootstrap/app.php:

->withMiddleware(function (Middleware $middleware): void {
    $middleware->trustHosts();
})

Filament

Register the plugin on your panel:

use EtienneScherrer\Traffic\Filament\TrafficPlugin;

->plugin(
    TrafficPlugin::make()
        ->authorize(fn (User $user): bool => $user->isAdmin())
        ->navigationGroup('Verwaltung')
)

->authorize() receives the user signed in on the panel's guard and decides who sees the page. Without it nobody does, so forgetting it never exposes the statistics. ->navigationGroup() is optional.

The plugin adds the page at /admin/statistics (in a panel at /admin): a from and until filter (the last 30 days by default, at most three years, ending today at the latest), a host picker when the period has more than one host, a chart of visitors and page views per day, and a table of the ten most visited pages. The labels come in German and English and follow the app's locale.

Your own page

To change the page, extend it and hand the subclass to the plugin:

use Carbon\CarbonImmutable;
use EtienneScherrer\Traffic\Filament\Pages\Statistics;
use EtienneScherrer\Traffic\Traffic;

class SeasonStatistics extends Statistics
{
    protected string $view = 'filament.pages.season-statistics';

    public static function defaultPeriod(): array
    {
        return [CarbonImmutable::parse('2026-11-01'), Traffic::today()->startOfDay()];
    }
}
TrafficPlugin::make()
    ->authorize(fn (User $user): bool => $user->isAdmin())
    ->page(SeasonStatistics::class)
  • defaultPeriod() returns the period the page opens with.
  • periodFrom(?array $filters) turns the filter data into the period shown. Override it to read the filters differently, and keep the bound it applies.
  • hostFrom(?array $filters) returns the chosen host, only if it had visits in the period.
  • $view replaces the page's content. Render $this->getFiltersForm() in it to keep the filters. The chart and the top pages are header and footer widgets and stay on a replaced view.

The chart and the table read the period and host through the page class registered on the plugin, so they follow a subclass. TrafficPlugin::get() throws a LogicException on a panel that does not register the plugin, so the page and its widgets work only on a panel that does.

Public API

All methods are static on EtienneScherrer\Traffic\Traffic:

Method Returns
visitorHash(Request $request) The visitor's hash for today, for an app that records its own events per visitor
today() Now, in the configured timezone
days(CarbonImmutable $from, CarbonImmutable $until, ?string $host = null) A collection keyed by Y-m-d with views and visitors for every day of the period, zero where nothing was counted
topPages(CarbonImmutable $from, CarbonImmutable $until, ?string $host = null, int $limit = 10) The most viewed pages with host, path, views and visitors
hosts(CarbonImmutable $from, CarbonImmutable $until) The hosts that had visits in the period
excludeWhen(Closure $callback) Registers an exclusion, see above

The visitors of a page in topPages() are the sum of its daily visitors: someone who reads the page on two days counts twice.

License

MIT