spatie/laravel-stats
Lightweight Laravel package to track and summarize stat changes over time. Define a stats class, call increase/decrease on events, then query totals and increments/decrements across date ranges grouped by day/week/month.
Strengths:
HasMany), and attributes, enabling multi-tenant or segmented analytics (e.g., per-tenant stats).increase(), decrease(), and set(), promoting clean architecture and observability.Fit for Use Cases:
Misalignment:
Laravel Compatibility:
Data Flow:
increase()/decrease() calls (e.g., in event listeners, controllers, or jobs). Example:
// In SubscriptionCancelled event listener
SubscriptionStats::decrease($subscription->created_at);
StatsQuery (e.g., in API endpoints or scheduled reports). Example:
$stats = SubscriptionStats::query()
->start(now()->subMonth())
->groupByWeek()
->get();
StatsWriter::for(User::class)).Database Schema:
stats) with columns:
statistic (string): Key (e.g., subscription_stats).attributes (json): Custom attributes (e.g., ['tenant_id': 1]).value (bigint): Current value.created_at (timestamp): Event timestamp.statistic, attributes, and created_at for performance.Performance:
increase()/decrease() (single DB insert).created_at range). Mitigate with:
Low Risk:
StatsWriter).Moderate Risk:
stats table by statistic or time).attributes or separate stat classes per tenant).Mitigation Strategies:
increase()/decrease() calls be placed (e.g., event listeners, jobs, controllers)?increase() in event listeners).SubscriptionStats, OrderStats) and their attributes.composer require spatie/laravel-stats
php artisan vendor:publish --provider="Spatie\Stats\StatsServiceProvider" --tag="stats-migrations"
php artisan migrate
app/Stats/SubscriptionStats.php).increase()/decrease() calls:
// Before: Manual increment in a controller
DB::table('metrics')->where('name', 'subscriptions')->increment('count');
// After: Using spatie/laravel-stats
SubscriptionStats::increase();
SubscriptionStats::set(100); // Set initial value
// API endpoint: /stats/subscriptions?period=monthly
return SubscriptionStats::query()
->start(now()->subMonth())
->groupByWeek()
->get();
BaseStats for custom logic (e.g., validation, hooks).StatsQuery for advanced aggregations.How can I help you explore Laravel packages today?