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
    

    Ensure your project uses PHP 8.2+ and Laravel 11+.

  2. First Use Case: Generate monthly trends for a model (e.g., Order):

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

    Output: Array of monthly counts (e.g., ['January' => 15, 'February' => 22]).

  3. Where to Look First:

    • README.md: For syntax, examples, and feature highlights.
    • Eliseekn\LaravelMetrics\LaravelMetrics: Core class for method chaining.
    • Demo Project: GitHub Demo for real-world integration.

Implementation Patterns

Core Workflows

1. Dashboard Metrics

  • Pattern: Chain methods to build reusable metric queries.
  • Example (Monthly Revenue by Status):
    $revenueByStatus = Order::metrics()
        ->sum('amount')
        ->byMonth(12)
        ->labelColumn('status')
        ->groupData(['pending', 'completed'], 'sum')
        ->fillMissingData()
        ->trends();
    
  • Use Case: Power charts in Laravel Nova, Livewire, or Inertia.js dashboards.

2. Time-Series Aggregations

  • Pattern: Combine between() with groupBy() for custom periods.
  • Example (Daily Active Users over 30 Days):
    $dau = UserActivity::metrics()
        ->count()
        ->between([
            now()->subDays(30)->format('Y-m-d'),
            now()->format('Y-m-d')
        ])
        ->groupByDay()
        ->fillMissingData(0)
        ->trends();
    
  • Use Case: Retention analysis, user engagement metrics.

3. Variation Analysis

  • Pattern: Compare current vs. previous periods.
  • Example (YoY Growth):
    $growth = Product::metrics()
        ->sum('sales')
        ->byYear(2)
        ->metricsWithVariations(1, 'year', true); // Previous year, % format
    
  • Use Case: Executive reports, A/B testing dashboards.

4. Model Traits

  • Pattern: Attach HasMetrics trait to Eloquent models for concise syntax.
  • Example:
    class Order extends Model {
        use \Eliseekn\LaravelMetrics\Traits\HasMetrics;
    }
    // Usage:
    $monthlyOrders = Order::metrics()->count()->byMonth()->trends();
    
  • Use Case: Domain-specific metrics (e.g., Invoice::metrics()).

5. Query Builder Integration

  • Pattern: Use raw SQL for complex joins.
  • Example (Joined Metrics):
    $userOrders = LaravelMetrics::query(
        DB::table('orders')
            ->join('users', 'orders.user_id', 'users.id')
    )
    ->count()
    ->table('users')
    ->labelColumn('country')
    ->byMonth()
    ->trends();
    

Integration Tips

  • Caching: Cache frequent queries (e.g., daily metrics) using Laravel’s cache:
    $metrics = Cache::remember('monthly_revenue', now()->addDay(), function () {
        return Order::metrics()->sum('amount')->byMonth()->metrics();
    });
    
  • API Responses: Format output for APIs:
    return response()->json([
        'data' => $trends,
        'period' => 'monthly',
        'unit' => 'count'
    ]);
    
  • Testing: Mock LaravelMetrics in unit tests:
    $this->partialMock(LaravelMetrics::class, function ($mock) {
        $mock->shouldReceive('query')->andReturnSelf();
        $mock->shouldReceive('count')->andReturnSelf();
        $mock->shouldReceive('byMonth')->andReturnSelf();
        $mock->shouldReceive('trends')->andReturn(['Jan' => 100]);
    });
    

Gotchas and Tips

Pitfalls

  1. Date Handling Quirks:

    • Issue: between() with groupByMonth() may exclude partial months. Fix: Use fillMissingData() to pad gaps.
    • PostgreSQL/SQLite: Ensure date columns are cast to Carbon to avoid SQL errors.
      ->dateColumn('created_at') // Explicitly specify date column
      
  2. Label Column Pitfalls:

    • Issue: labelColumn() requires distinct values; duplicates cause aggregation errors. Fix: Use groupData() for multi-value labels:
      ->groupData(['active', 'inactive'], 'count')
      
  3. Performance:

    • Issue: Complex between() queries with large date ranges slow down. Fix: Limit periods (e.g., byMonth(6)) or add database indexes:
      CREATE INDEX orders_monthly ON orders(created_at(6)); -- MySQL
      
  4. Trailing Methods:

    • Issue: Forgetting ->trends() or ->metrics() returns raw data. Fix: Chain methods explicitly:
      ->byMonth()->trends(); // Correct
      ->byMonth(); // Returns LaravelMetrics instance (no data)
      
  5. Locale Translations:

    • Issue: Month/day names may not translate in non-English apps. Fix: Set config(['app.locale' => 'fr']) before querying.

Debugging Tips

  • Verbose Queries: Enable Laravel’s query logging:
    DB::enableQueryLog();
    $metrics = LaravelMetrics::query(...)->trends();
    dd(DB::getQueryLog()); // Inspect raw SQL
    
  • Missing Data: Use fillMissingData() with a default value:
    ->fillMissingData(0) // Fill zeros for missing dates
    
  • PostgreSQL Errors: Check for reserved keyword conflicts (e.g., order table):
    ->table('"order"') // Escape with quotes
    

Extension Points

  1. Custom Aggregates:

    • Extend the package by creating a custom aggregate method:
      // app/Extensions/LaravelMetrics.php
      namespace App\Extensions;
      use Eliseekn\LaravelMetrics\LaravelMetrics as BaseMetrics;
      
      class LaravelMetrics extends BaseMetrics {
          public function customAggregate(string $column) {
              return $this->addSelect("CONCAT({$column}, ' suffix') as custom_agg");
          }
      }
      
    • Override the facade in config/laravel-metrics.php:
      'metrics_class' => \App\Extensions\LaravelMetrics::class,
      
  2. Event Triggers:

    • Hook into metric generation to log or notify:
      LaravelMetrics::macro('afterTrends', function ($callback) {
          $callback($this->getTrendsData());
      });
      // Usage:
      LaravelMetrics::query(...)->byMonth()->afterTrends(fn($data) => Log::info($data));
      
  3. Database-Specific Optimizations:

    • Override the query builder for PostgreSQL/MySQL:
      // app/Providers/AppServiceProvider.php
      use Eliseekn\LaravelMetrics\Database\QueryBuilder;
      
      public function boot() {
          if (app()->environment('production')) {
              QueryBuilder::macro('optimizeForPostgres', function () {
                  // Custom PostgreSQL optimizations
              });
          }
      }
      

Pro Tips

  • Combine with Laravel Scout: Use metrics to power search relevance:
    $popularTags = Tag::metrics()
        ->count()
        ->byMonth(3)
        ->orderByDesc('count')
        ->limit(5)
        ->get();
    
  • Dynamic Periods: Calculate periods dynamically:
    $period = request('period', 'month');
    $method = "by{$period}";
    $metrics = LaravelMetrics::query(...)->$method()->trends();
    
  • Visualization Libraries:
    • Pair with Chart.js or ApexCharts for seamless integration:
      // Inertia.js example
      const labels = @json($trends->keys());
      const data = @json($trends->values());
      new Chart(ctx, { type: 'line', data: { labels, datasets: [{ data }] } });
      
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