Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Stats Laravel Package

spatie/laravel-stats

Lightweight Laravel package that summarizes database changes over time. Define a stats class, call increase() or decrease() as events happen, then query totals grouped by day, week, or month, returning increments, decrements, and net differences for each period.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture fit

  • Strong fit for Laravel monoliths or modular Laravel applications that need lightweight, database-backed counters for business/product metrics such as signups, subscriptions, cancellations, orders, or feature usage.
  • The package is not an analytics platform. It records stat changes as database events and aggregates at query time into time buckets. It does not provide dashboards, alerting, retention policies, downsampling, or cross-service ingestion.
  • Fits best when metrics are low-to-moderate volume and already owned by the Laravel application. Poor fit for high-cardinality event analytics, high-throughput telemetry, or metrics that must be shared across non-Laravel services.
  • The BaseStats, StatsWriter, StatsQuery, and HasStats abstractions are Laravel-native and align with Eloquent models, relationships, multi-tenant patterns, and custom attributes.

Integration feasibility

  • Low initial integration cost: Composer install, publish/run migration, create a BaseStats subclass, call increase/decrease/set, and query with StatsQuery.
  • Supports useful extension paths: custom stat names, custom models via HasStats, model/class/relationship writers, custom attribute filters, and group-by minute/hour/day/week/month/year.
  • Historical writes are possible via optional timestamps, which helps backfilling from existing source records, but the package does not provide a formal backfill or reconciliation tool.
  • Main feasibility question is not installation effort; it is whether the team can guarantee accurate, exactly-once stat writes from domain events.

Technical risk

  • Event accuracy risk: stats are only as correct as the calls to increase/decrease/set. Missing calls, failed listeners, retries, or duplicated domain events can permanently skew counts unless wrappers, idempotency, and reconciliation are designed.
  • Query-time aggregation risk: the package appears to store individual stat changes and aggregate over selected ranges. Large event tables will increase storage and query latency; without rollups, partitioning, or retention, reporting performance degrades over time.
  • Semantics risk: set, increase, and decrease need clear operational semantics, especially when mixing fixed-value snapshots with change events. Teams must understand how value, increments, decrements, and difference are computed to avoid double counting.
  • Time and reporting risk: date grouping must be validated for timezone, DST, fiscal calendar, and “as-of” reporting expectations. Bucket boundaries may not match finance or product definitions without additional normalization.
  • Ecosystem risk: Spatie packages are generally well maintained, but 451 stars and reported zero dependents indicate limited public production evidence. Internal ownership and validation remain necessary.
  • Operational risk: no built-in pruning, aggregation, alerting, or anomaly detection. These must be built or accepted as gaps.

Key questions

  • What event volume and retention window are expected per stat, and what query latency is acceptable?
  • Is the metric a business-critical source of truth, or a lightweight product signal?
  • Do we need exactly-once counting, and what is the source of truth for reconciliation?
  • Will stats be written inside domain transactions, after commit, via queue, or through an outbox?
  • What are the timezone, DST, and reporting-period requirements?
  • Is multi-tenancy required, and should tenant scoping use relationships or custom attributes?
  • Do we need historical backfill from existing records, and is event history available?
  • Which Laravel, PHP, and database versions must be supported?
  • Will this feed dashboards, billing, finance, or only internal exploration?
  • Who owns schema migrations, indexes, retention, and metric reconciliation after launch?

Integration Approach

Stack fit

  • Verify Composer constraints against the target Laravel and PHP versions before adoption. Changelog history shows Laravel 9 through Laravel 13 support and PHP 8.2-era compatibility, but the exact matrix should be confirmed for the application’s locked versions.
  • Confirm database support and behavior for the target engine. Changelog references PostgreSQL, SQLite, and table-prefix fixes; MySQL is likely common but should be validated with actual queries and date grouping.
  • Use a thin internal wrapper around the package rather than scattering static increase/decrease calls throughout controllers and models. The wrapper should own stat naming, metadata, timestamp handling, idempotency strategy, and failure behavior.
  • For multi-tenant or domain-scoped metrics, prefer StatsWriter::for() with models, relationships, or custom attributes rather than creating many near-duplicate BaseStats classes.

Migration path

  • Start with a non-critical metric that has a clear source of truth and a small number of write points.
  • Install the package, publish and run the migration in a non-production environment, then inspect the generated schema and add any missing composite indexes for common query patterns such as stat name/type plus timestamp.
  • Instrument one domain event through the internal wrapper and compare package counts against the existing source-of-truth query for a defined period.
  • If historical reporting is required, backfill from existing records using the package’s timestamp support, but validate whether historical increase/decrease or set semantics match the desired metric.
  • Run dual-write or shadow reporting before switching any dashboard or business process to package-derived numbers.
  • Expand to additional metrics only after write accuracy, query latency, and retention behavior are understood.

Compatibility

  • Validate package behavior with the application’s database driver, table prefix configuration, timezone settings, and any read/write splitting configuration.
  • Confirm whether stats writes should participate in existing transactions. If the domain transaction rolls back, the stat write should usually roll back too; if stats are analytical and non-critical, after-commit or queued writes may be preferable but introduce delay and loss risk.
  • Confirm relationship support if used; the changelog notes relationships were added with “has-many” support and other relationship types were untested at that time.
  • Check whether existing reporting models, BI tools, or export jobs expect a different schema or metric definition.

Sequencing

  1. Discovery: define metric semantics, source of truth, volume, retention, and reporting periods.
  2. Technical spike: install in a branch, run migration, exercise increase/decrease/set and grouped queries against representative data.
  3. Instrumentation design: create wrapper, choose transaction/queue strategy, define idempotency and failure handling.
  4. Pilot: instrument one metric, reconcile for at least one full reporting cycle, measure query latency and table growth.
  5. Reporting integration: connect queries to internal dashboards or exports only after reconciliation passes.
  6. Expansion: add metrics incrementally, with per-metric ownership and validation.
  7. Hardening: add indexes, retention/pruning, rollups or archival if volume justifies it, and operational alerts.

Operational Impact

Maintenance

  • Low code maintenance if usage remains simple: package updates, migration management, and routine dependency review.
  • Ongoing operational maintenance includes monitoring table growth, query latency, index effectiveness, and failed stat writes.
  • The package does not appear to include built-in retention or rollup management. Plan for pruning, archival, partitioning, or materialized summaries if event volume grows.
  • Class or stat-name changes can orphan historical data; treat stat names as stable identifiers and document ownership.

Support

  • Community-supported open-source package under MIT, backed by Spatie’s generally strong package quality and documentation.
  • No formal SLA or vendor support. The adopting team must own incident response for metric discrepancies, schema changes, and performance issues.
  • Limited public dependents reduce external production evidence; internal runbooks and reconciliation checks are important.
  • Security and access controls are inherited from the Laravel application and database; business-sensitive metrics should follow existing data-access policies.

Scaling

  • Write scaling is roughly one database row per stat change, so high-volume domains can create large tables and write pressure.
  • Read scaling depends on range size and grouping. Long date ranges over large event tables can become expensive; dashboards should use bounded ranges and cached or pre-aggregated results.
  • For higher scale, introduce rollup tables, scheduled aggregation jobs, partitioning, read replicas, or a dedicated analytics store. At that point, reassess whether the package remains the right system of record.
  • Batch or queued writes may reduce request latency but complicate freshness and loss handling.

Failure modes

  • Missing stat writes due to missed instrumentation, failed listeners, queue failures, or rolled-back transactions.
  • Duplicate counts due to retries, duplicate domain events, or non-idempotent handlers.
  • Incorrect historical values due to timezone/DST bucket behavior, out-of-order writes, or misunderstood set versus increase/decrease semantics.
  • Slow or timing-out reports as the event table grows.
  • Schema or migration issues during Laravel/database upgrades.
  • Silent metric drift with no built-in anomaly detection or alerting.
  • Multi-tenant leakage if scoping relies on custom attributes or relationships that are not consistently enforced.

Ramp-up

  • A Laravel developer can become productive with the package in hours to a day: create a stat class, write increases/decreases, and run grouped queries.
  • Production readiness takes longer because the team must design event accuracy, transaction boundaries, backfill, reconciliation, indexing, retention, and reporting semantics.
  • Budget additional effort for analytics stakeholders to agree on metric definitions, timezone handling, and source-of-truth reconciliation before relying on the numbers.
  • Recommended ramp-up: start with one low-risk metric, operate it through a full reporting cycle, document the runbook, then expand.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
tequilarapido/trackit
gregsphotography/site-builder-filament
cabaoctavio/laravel-query-log
gregsphotography/site-builder-components
io-digital/clickatell
snowsoft/laravel-admin
oxygen/auth
relicsoftware/barakah-payment-gateway
tobya/work-with-composer
equipc/laravel-email-validator
equipc/laravel-email-database-log
adedsec/nova-translated-labels
wazza/laravel-db-encryption
hokny/laravel-generator
vonsogt/backup
jengo/queues
jeremykenedy/laravel-observability
coleus/frame
thtg88/journalism
filagora/filagora-ai-forums