Weave Code
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 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.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Strengths:

    • Lightweight & Modular: The package is designed for granular, time-series tracking of business metrics (e.g., subscriptions, orders, users) with minimal overhead. It aligns well with Laravel’s ecosystem and follows Laravel conventions (e.g., service providers, migrations).
    • Flexible Querying: Supports time-based aggregation (minute, hour, day, week, month, year) and customizable grouping, making it ideal for analytics dashboards or reporting tools.
    • Extensible: Supports custom models, relationships (e.g., HasMany), and attributes, enabling multi-tenant or segmented analytics (e.g., per-tenant stats).
    • Event-Based: Decouples stat updates from business logic via increase(), decrease(), and set(), promoting clean architecture and observability.
    • Database Agnostic: Works with MySQL, PostgreSQL, SQLite, and others, reducing vendor lock-in.
  • Fit for Use Cases:

    • Core Analytics: Tracking KPIs (e.g., DAU, MAU, revenue metrics) with historical trends.
    • Multi-Tenant Systems: Segmented stats per tenant/user (via custom attributes or relationships).
    • Audit/Compliance: Recording changes over time (e.g., subscription cancellations, order volumes).
    • Real-Time Dashboards: Lightweight queries for time-series data visualization (e.g., with Chart.js or Laravel Nova).
  • Misalignment:

    • Not for Complex Aggregations: Lacks built-in support for multi-dimensional analytics (e.g., cohort analysis, funnel conversion). Requires post-processing.
    • No Built-in Caching: Queries hit the database directly; caching (e.g., Redis) must be layered externally.
    • Limited to Numeric Stats: Focuses on counters; not suited for categorical or non-quantitative metrics.

Integration Feasibility

  • Laravel Compatibility:

    • Seamless: Designed for Laravel 9–13, with PHP 8.1+ support. Leverages Laravel’s service container, migrations, and Eloquent.
    • Dependencies: Minimal (only Laravel core and PHP extensions). No external services required.
    • Testing: Includes CI/CD and unit tests, reducing integration risk.
  • Data Flow:

    • Write Path: Business logic triggers increase()/decrease() calls (e.g., in event listeners, controllers, or jobs). Example:
      // In SubscriptionCancelled event listener
      SubscriptionStats::decrease($subscription->created_at);
      
    • Read Path: Queries via StatsQuery (e.g., in API endpoints or scheduled reports). Example:
      $stats = SubscriptionStats::query()
          ->start(now()->subMonth())
          ->groupByWeek()
          ->get();
      
    • Custom Models: Supports writing/reading stats tied to Eloquent models (e.g., StatsWriter::for(User::class)).
  • Database Schema:

    • Migrations: Publishes a single table (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.
    • Indexing: Assumes proper indexing on statistic, attributes, and created_at for performance.
  • Performance:

    • Write: O(1) for increase()/decrease() (single DB insert).
    • Read: O(n) for time-range queries (scans created_at range). Mitigate with:
      • Database indexes (already present in migrations).
      • Query optimization (e.g., limit time ranges).
      • Caching frequent queries (e.g., Redis).

Technical Risk

  • Low Risk:

    • Mature Package: Actively maintained (releases every 3–6 months), with 450+ stars and contributions from the Laravel community.
    • Minimal Breaking Changes: Major version (2.x) introduced backward-compatible features (e.g., StatsWriter).
    • Documentation: Comprehensive README, CHANGELOG, and upgrade guide.
  • Moderate Risk:

    • Query Performance: Large datasets may require tuning (e.g., partitioning stats table by statistic or time).
    • Custom Logic: Advanced use cases (e.g., custom aggregations) may need custom queries or extensions.
    • Multi-Tenant Isolation: Requires explicit handling (e.g., via attributes or separate stat classes per tenant).
  • Mitigation Strategies:

    • Benchmark: Test with expected dataset size (e.g., 1M+ events) to validate query performance.
    • Caching Layer: Cache frequent queries (e.g., Redis with tags for invalidation).
    • Monitoring: Track query durations and DB load (e.g., Laravel Debugbar or New Relic).

Key Questions for TPM

  1. Use Case Clarity:
    • What specific metrics will be tracked (e.g., subscriptions, orders, users)?
    • Are stats global or segmented (e.g., per tenant, region, user role)?
  2. Scale Requirements:
    • Expected write/read volume (e.g., events/sec, queries/sec)?
    • Will stats be queried in real-time or batch-processed?
  3. Integration Points:
    • Where will increase()/decrease() calls be placed (e.g., event listeners, jobs, controllers)?
    • How will stats be surfaced (e.g., API endpoints, admin dashboard, third-party tools)?
  4. Customization Needs:
    • Are custom aggregations (e.g., moving averages) required?
    • Will stats be extended to non-numeric data (e.g., status flags)?
  5. Operational Constraints:
    • Are there SLA requirements for query latency?
    • How will data retention/purging be managed (e.g., TTL policies)?

Integration Approach

Stack Fit

  • Laravel Ecosystem:
    • Native Integration: Works out-of-the-box with Laravel’s service container, migrations, and Eloquent.
    • Event-Driven: Aligns with Laravel’s event system (e.g., trigger increase() in event listeners).
    • API-Friendly: Easy to expose stats via Laravel API resources or GraphQL.
  • Database:
    • Supported: MySQL, PostgreSQL, SQLite (tested). Avoid unsupported DBs (e.g., SQL Server).
    • Schema: Lightweight (single table). No complex joins required for basic use.
  • Frontend/Analytics:
    • Visualization: Compatible with libraries like Chart.js, Highcharts, or Laravel Nova cards.
    • Export: Can be extended to support CSV/Excel exports for reporting.

Migration Path

  1. Assessment Phase:
    • Audit existing metrics tracking (e.g., manual logs, custom tables).
    • Define stat classes (e.g., SubscriptionStats, OrderStats) and their attributes.
  2. Setup:
    • Install package:
      composer require spatie/laravel-stats
      php artisan vendor:publish --provider="Spatie\Stats\StatsServiceProvider" --tag="stats-migrations"
      php artisan migrate
      
    • Create stat classes (e.g., app/Stats/SubscriptionStats.php).
  3. Instrumentation:
    • Replace manual tracking with increase()/decrease() calls:
      // Before: Manual increment in a controller
      DB::table('metrics')->where('name', 'subscriptions')->increment('count');
      
      // After: Using spatie/laravel-stats
      SubscriptionStats::increase();
      
    • For existing data, backfill via a seed or job:
      SubscriptionStats::set(100); // Set initial value
      
  4. Query Layer:
    • Build API endpoints or dashboard queries:
      // API endpoint: /stats/subscriptions?period=monthly
      return SubscriptionStats::query()
          ->start(now()->subMonth())
          ->groupByWeek()
          ->get();
      
  5. Testing:
    • Unit test stat updates and queries.
    • Load test with expected volume (e.g., 10K writes/sec).
  6. Deployment:
    • Roll out in phases (e.g., non-critical stats first).
    • Monitor DB performance and query latency.

Compatibility

  • Laravel Versions: 9–13 (tested). Avoid unsupported versions (e.g., 8.x).
  • PHP Versions: 8.1+. Avoid 7.x.
  • Database: MySQL 5.7+, PostgreSQL 10+, SQLite 3.34+. Test with target DB.
  • Dependencies:
    • No conflicts with common Laravel packages (e.g., Laravel Nova, Cashier).
    • Avoid packages that modify core DB behavior (e.g., custom query builders).
  • Custom Extensions:
    • Extend BaseStats for custom logic (e.g., validation, hooks).
    • Override StatsQuery for advanced aggregations.

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.
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony
develia/geo-bundle
dreamzy/livewire-charts
touchestate-sdk/php-sdk
ecotone/kafka
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin
splash/metadata