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 Metrics Laravel Package

eliseekn/laravel-metrics

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require eliseekn/laravel-metrics
    

    Publish the config (if needed):

    php artisan vendor:publish --provider="Eliseekn\LaravelMetrics\LaravelMetricsServiceProvider"
    
  2. First Use Case: Generate a simple trend for a model (e.g., Product):

    use Eliseekn\LaravelMetrics\LaravelMetrics;
    
    $trends = LaravelMetrics::query(Product::query())
        ->count()
        ->byMonth()
        ->trends();
    

    This returns an array of monthly counts for the current year.

  3. Where to Look First:

    • README: Focus on the "Usage" section for syntax and examples.
    • Config: Check config/metrics.php for default settings (e.g., date formatting, timezones).
    • Facade: Explore LaravelMetrics methods in src/Facades/LaravelMetrics.php.

Implementation Patterns

Core Workflows

  1. Query Chaining: Use the fluent interface to build metrics:

    LaravelMetrics::query(User::query())
        ->where('active', true)
        ->sum('purchases')
        ->byMonth(3) // Last 3 months
        ->metrics(); // Returns raw metrics
    
  2. Date Granularity:

    • Daily: byDay(7) → Last 7 days.
    • Monthly: byMonth(6) → Last 6 months.
    • Yearly: byYear() → All years in the table.
    • Custom: Use byCustom($startDate, $endDate) with Carbon instances.
  3. Aggregations:

    • count(): Row count.
    • sum('column'): Sum of a column (e.g., sum('revenue')).
    • avg('column'): Average value.
    • min('column')/max('column'): Extremes.
  4. Output Modes:

    • metrics(): Raw aggregated data (e.g., ['2024-01' => 150, '2024-02' => 200]).
    • trends(): Pre-formatted for charts (includes dates and values).
  5. Custom Columns: For non-standard aggregations, use selectRaw():

    LaravelMetrics::query(Order::query())
        ->selectRaw('SUM(amount) as total_amount')
        ->byMonth()
        ->metrics();
    

Integration Tips

  • Dashboards: Pair with Laravel Nova, Livewire, or InertiaJS for real-time rendering.
  • Caching: Cache results for performance:
    $metrics = Cache::remember('user_metrics_monthly', now()->addHours(1), function () {
        return LaravelMetrics::query(User::query())->count()->byMonth()->metrics();
    });
    
  • APIs: Return trends as JSON:
    return response()->json(LaravelMetrics::query(Product::query())->count()->byMonth()->trends());
    
  • Testing: Mock the facade in unit tests:
    LaravelMetrics::shouldReceive('query')->andReturnSelf()
        ->shouldReceive('count')->andReturnSelf()
        ->shouldReceive('byMonth')->andReturnSelf()
        ->shouldReceive('trends')->andReturn(['2024-01' => 100]);
    

Gotchas and Tips

Pitfalls

  1. Date Handling:

    • Timezones: Ensure your app’s timezone (config/app.php) matches your database’s timezone. Metrics use Carbon under the hood.
    • Custom Dates: byCustom() expects Carbon instances or strings parsable by Carbon. Invalid dates may throw exceptions. Fix: Validate inputs:
      $start = Carbon::parse($request->start_date);
      $end = Carbon::parse($request->end_date);
      
  2. Query Complexity:

    • Nested Relationships: Avoid deep relationships in the base query—metrics generate subqueries, which can bloat SQL. Workaround: Eager-load only necessary relationships:
      LaravelMetrics::query(Product::with('category')->query())
          ->count()
          ->byMonth();
      
    • Group By Conflicts: If your query has groupBy(), metrics may override it. Use selectRaw() for custom groupings.
  3. Performance:

    • Large Datasets: Yearly metrics on tables with millions of rows may time out. Tip: Add database indexes to filtered columns (e.g., created_at).
    • Memory Limits: Complex aggregations (e.g., sum() on large decimal columns) can hit PHP’s memory limit. Fix: Increase memory_limit or chunk queries:
      LaravelMetrics::query(Order::query()->take(1000))->sum('amount')->byMonth();
      
  4. SQLite Quirks:

    • SQLite lacks some MySQL/PostgreSQL functions (e.g., DATE_FORMAT). Use Carbon’s accessors instead:
      ->selectRaw('strftime("%Y-%m", created_at) as month')
      

Debugging

  1. Verbose Queries: Enable query logging to inspect generated SQL:

    LaravelMetrics::setDebug(true);
    

    Or use Laravel’s built-in logging:

    DB::enableQueryLog();
    $metrics = LaravelMetrics::query(...);
    dd(DB::getQueryLog());
    
  2. Common Errors:

    • "Column not found": Ensure the column exists in the table or use selectRaw().
    • "Invalid argument": Check date formats in byCustom() or byMonth().
    • Empty Results: Verify the base query returns rows (e.g., add ->get() to debug).

Extension Points

  1. Custom Aggregations: Extend the package by creating a custom metric class:

    namespace App\Metrics;
    
    use Eliseekn\LaravelMetrics\Contracts\Metric;
    
    class CustomMetric implements Metric {
        public function apply($query) {
            return $query->selectRaw('AVG(price) as avg_price');
        }
    }
    

    Register it in config/metrics.php under custom_metrics.

  2. Date Translations: Override default date formatting in the config:

    'date_formats' => [
        'day' => 'Y-m-d H:i',
        'month' => 'Y-m',
        'year' => 'Y',
    ],
    
  3. Database-Specific Optimizations: Add database-specific query tweaks via service provider booting:

    public function boot() {
        if (app()->database->getDriverName() === 'pgsql') {
            LaravelMetrics::extend(function ($metrics) {
                $metrics->query->addSelect(DB::raw('DATE_TRUNC(\'month\', created_at) as month'));
            });
        }
    }
    
  4. Testing: Use the MetricsTestCase trait (if provided) or mock the facade:

    use Eliseekn\LaravelMetrics\Testing\MetricsTestCase;
    
    class MyTest extends TestCase {
        use MetricsTestCase;
    }
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
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