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

Metrics Laravel Package

directorytree/metrics

Record and query metrics in Laravel with a simple, elegant API. Track page views, API calls, signups, and other events with optional values, categories, dates, hourly buckets, model-scoped metrics, and custom attributes. Supports Redis and extensible drivers.

View on GitHub
Deep Wiki
Context7

Technical Evaluation

Architecture Fit

  • Event-Driven Metrics Collection: The package excels in tracking countable events (e.g., page views, API calls, user actions) with minimal overhead, aligning well with Laravel’s event-driven architecture. The ability to batch metrics via Redis or in-memory capture reduces database load, making it ideal for high-traffic applications.
  • Granularity & Segmentation: Supports daily, hourly, and custom-date metrics, as well as categorization and custom attributes (e.g., source, country). This enables fine-grained analytics without requiring external tools like Mixpanel or Google Analytics.
  • Model Association: The HasMetrics trait integrates seamlessly with Eloquent, enabling per-model tracking (e.g., user-specific metrics). This is particularly useful for SaaS platforms or applications with user-centric analytics.
  • Extensibility: Custom metric models, repositories, and managers allow tailoring to niche use cases (e.g., multi-tenant metrics, custom storage backends).

Integration Feasibility

  • Laravel Native: Built for Laravel 9+, leveraging facades, service providers, and Eloquent, ensuring smooth integration with existing Laravel applications.
  • Database Agnostic: Uses Laravel migrations and Eloquent, so it works with any supported database (MySQL, PostgreSQL, SQLite).
  • Redis Support: Optional Redis driver for distributed systems or high-write scenarios, reducing database contention. Requires minimal setup (configuration + scheduled job).
  • Queue Integration: Metrics can be committed asynchronously via queues (e.g., metrics:commit command), further decoupling metric recording from database writes.

Technical Risk

  • Performance at Scale:
    • Hourly Metrics: Storing hourly metrics creates 24x more rows than daily metrics. For high-frequency metrics (e.g., API calls), this could bloat the database. Mitigation: Use hourly metrics sparingly or implement TTL-based cleanup.
    • Custom Attributes: Adding custom columns to the metrics table requires manual migration and may not scale for arbitrary attributes. Mitigation: Use a JSON column or a separate pivot table for dynamic attributes.
  • Distributed Systems:
    • Redis driver relies on a scheduled job (metrics:commit) to flush metrics to the database. If the job fails or Redis is unavailable, metrics may be lost. Mitigation: Monitor the job and implement retries/fallbacks.
    • No built-in support for multi-region deployments. Metrics recorded in one region may not sync to others without additional logic.
  • Backfilling:
    • Backfilling historical metrics (e.g., date(Carbon::parse('2025-01-15'))) requires careful handling to avoid duplicates or conflicts. Mitigation: Implement idempotent recording logic or use transactions.
  • Testing Complexity:
    • Querying metrics in tests (e.g., Metric::fake()) may require mocking the underlying storage layer. The package lacks a robust fake implementation out of the box.

Key Questions

  1. Use Case Alignment:
    • Are metrics primarily for real-time dashboards, historical reporting, or both? This dictates whether hourly granularity or batch processing is prioritized.
    • Will metrics be used for user-specific analytics (e.g., per-user activity) or aggregate trends (e.g., global traffic)? This affects the need for measurable() and custom attributes.
  2. Scalability Requirements:
    • What is the expected write volume (e.g., metrics/sec)? For >10k writes/sec, consider a dedicated time-series database (e.g., InfluxDB) alongside this package.
    • Is multi-tenancy required? The package doesn’t natively support tenant isolation; this would need customization.
  3. Operational Constraints:
    • Can the team maintain a scheduled job (metrics:commit) for Redis-based batching? If not, in-memory capturing may be preferable.
    • Are there compliance requirements (e.g., GDPR) for storing user-associated metrics? Custom attributes tied to users may need anonymization or retention policies.
  4. Observability:
    • How will metric accuracy be validated? For example, ensuring sum('value') matches expected totals.
    • Are there SLA requirements for metric availability (e.g., 99.9% uptime)? This impacts redundancy and backup strategies.

Integration Approach

Stack Fit

  • Laravel Ecosystem: Perfectly aligned with Laravel’s conventions (facades, Eloquent, migrations, queues). No major framework changes required.
  • Database: Works with any Laravel-supported database. For high-write scenarios, consider:
    • PostgreSQL: Better for JSON attributes and partitioning.
    • MySQL: Add indexes on name, category, measurable_type/id, and custom attributes for query performance.
  • Caching: Redis is optional but recommended for distributed systems. Alternatives like Memcached could be substituted with minor code changes.
  • Queue Systems: Supports Laravel queues (database, Redis, etc.) for async metric commits. For high throughput, consider dedicated queue workers.

Migration Path

  1. Pilot Phase:
    • Start with daily metrics and basic categories (e.g., api:requests, signups).
    • Use the database driver (no Redis) to validate core functionality.
    • Integrate with existing analytics pipelines (e.g., export metrics to a data warehouse via a scheduled job).
  2. Scaling Phase:
    • Enable Redis driver for high-traffic endpoints (e.g., API routes).
    • Schedule metrics:commit hourly or via queue workers.
    • Add custom attributes for segmentation (e.g., source, user_id).
  3. Advanced Phase:
    • Implement hourly metrics for time-sensitive use cases (e.g., real-time dashboards).
    • Extend with custom metric models or repositories for specialized needs (e.g., multi-tenancy).
    • Integrate with third-party tools (e.g., Grafana, DataDog) via API endpoints that query the Metric model.

Compatibility

  • Laravel Versions: Tested on Laravel 9+. For Laravel 10+, verify compatibility with new features (e.g., model macros, query builder changes).
  • PHP Versions: Requires PHP 8.1+. Ensure your environment supports named arguments, attributes, and other 8.1+ features.
  • Dependencies: Conflicts unlikely, but check for version constraints with other packages (e.g., spatie/laravel-analytics).
  • Customizations: The package is designed to be extended. For example:
    • Override the Metric model to add soft deletes or additional scopes.
    • Replace the repository to use a different storage backend (e.g., DynamoDB).

Sequencing

  1. Setup:
    • Install via Composer: composer require directorytree/metrics.
    • Publish migrations and config: php artisan vendor:publish --tag="metrics-migrations" --tag="metrics-config".
    • Run migrations: php artisan migrate.
  2. Configuration:
    • Choose a driver (database or redis) in config/metrics.php.
    • For Redis, configure TTL and queue settings.
  3. Integration:
    • Add metric recording to critical paths (e.g., route middleware, event listeners, job handlers).
    • Example:
      // app/Http/Middleware/RecordApiRequests.php
      public function handle(Request $request, Closure $next) {
          metric('api:requests')->record();
          return $next($request);
      }
      
  4. Validation:
    • Write unit tests for metric recording (e.g., verify metric('test')->record() increments the count).
    • Test query methods (e.g., Metric::today()->sum('value')).
  5. Monitoring:
    • Set up alerts for failed metrics:commit jobs.
    • Monitor database growth for hourly metrics or custom attributes.

Operational Impact

Maintenance

  • Package Updates: Monitor for updates to the directorytree/metrics package. Since it’s MIT-licensed and actively maintained (last release: 2026-04-17), updates are likely to be backward-compatible.
  • Database Schema: Custom attributes require manual migration changes. Document these in your schema migration scripts.
  • Configuration: Centralized in config/metrics.php, making it easy to adjust drivers, TTLs, or queue settings.
  • Dependencies: Minimal external dependencies (only Laravel core and Redis if used). No major third-party services to manage.

Support

  • Troubleshooting:
    • Missing Metrics: Check if auto_commit is enabled (disables Redis batching) or if the metrics:commit job is failing.
    • Query Performance: Add indexes to metrics table for name, category, measurable_type, measurable_id, and custom attributes.
    • Redis Issues: Monitor Redis memory usage and TTL expiration. Ensure the metrics:commit job runs reliably.
  • Documentation: README is comprehensive but lacks deep-dive examples (e.g., multi-tenancy, advanced querying). Supplement with internal docs.
  • Community: Limited community (263 stars, no depend
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.
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope