- How do I install DirectoryTree/Metrics in a Laravel 9+ project?
- Run `composer require directorytree/metrics`, publish the migrations with `php artisan vendor:publish --tag=metrics-migrations`, and execute `php artisan migrate`. Optional: Publish the config file with `--tag=metrics-config` for customization.
- What Laravel versions does DirectoryTree/Metrics support?
- The package officially supports Laravel 9 and 10. For Laravel 10, verify compatibility with new Eloquent features, but the core functionality remains stable. Always check the latest release notes for updates.
- Can I track hourly metrics without bloating my database?
- Yes, hourly metrics are supported via the `hourly()` method, but use disciplined naming (e.g., `api:requests.hourly`) to avoid confusion. For high-volume apps, consider Redis to offload writes and reduce database load.
- How do I record metrics for specific models (e.g., User, Order)?
- Use the `HasMetrics` trait on your model and call `recordMetric()` or `incrementMetric()` on instances. Example: `$user->recordMetric('profile_views')`. Model-scoped metrics are stored with the model’s ID for segmentation.
- Does DirectoryTree/Metrics support custom attributes for segmentation?
- Yes, you can add custom attributes like `user_id` or `plan_type` when recording metrics. These require manual migration updates (e.g., `metrics_attributes` table) and are queried via `whereAttribute()` in Eloquent queries.
- When should I use the Redis driver instead of the default database driver?
- Use Redis for high-throughput apps (e.g., 10K+ RPS) where database writes are a bottleneck. It improves performance but introduces eventual consistency (5-minute delay) and requires monitoring for TTL expiry or commit failures.
- How do I query metrics for a specific date range or category?
- Use Eloquent’s query builder: `Metrics::where('name', 'api_calls')->betweenDates('2023-01-01', '2023-01-31')` or `Metrics::whereCategory('auth')->thisMonth()`. Hourly metrics can be filtered with `whereHourly(true)`.
- Are there any risks of race conditions when recording metrics?
- Yes, high-traffic apps may experience race conditions during commits. Mitigate this by disabling `auto_commit` and manually committing via queues (e.g., `Metrics::commit()` in a job) or using Redis with proper locking mechanisms.
- How do I fake metrics in PHPUnit tests?
- Use the `Metrics::fake()` helper to stub metric recordings. Example: `Metrics::fake()->shouldRecord('page_views', 5)`. This prevents actual database writes during tests and verifies expected calls.
- What alternatives exist for Laravel metrics if DirectoryTree/Metrics doesn’t fit?
- Consider `spatie/laravel-analytics` for Google Analytics integration, `laravel-activitylog` for event logging, or `statsd` for high-scale time-series metrics. For custom solutions, Laravel’s Eloquent + queues can manually track metrics with less abstraction.