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

flowframe/laravel-trend

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require flowframe/laravel-trend
    

    Publish the config (if needed) with:

    php artisan vendor:publish --provider="Flowframe\Trend\TrendServiceProvider"
    
  2. First Use Case: Generate a simple monthly trend for a model (e.g., User):

    use Flowframe\Trend\Trend;
    
    $trend = Trend::model(User::class)
        ->between(
            start: now()->subMonths(6),
            end: now()
        )
        ->perMonth()
        ->count();
    

    This returns a Collection of arrays with keys: period, value, and total.

  3. Where to Look First:

    • README: Focus on the "Usage" section for basic syntax.
    • Config: Check config/trend.php for default time periods and aggregation methods.
    • Tests: Browse tests/ for edge cases and advanced usage (e.g., custom periods).

Implementation Patterns

Core Workflows

  1. Model vs. Query Trends:

    • Use Trend::model(Model::class) for simple trends on the entire table.
    • Use Trend::query(Model::query()) to add Eloquent filters (e.g., where, with):
      Trend::query(User::where('active', true))
          ->between(...)
          ->perWeek()
          ->average('score');
      
  2. Time Aggregation:

    • Chain methods like perMinute(), perHour(), perDay(), etc., to group data.
    • Custom periods via period(fn (Carbon $date) => ...):
      ->period(fn ($date) => $date->startOfWeek())
      
  3. Aggregation Methods:

    • count(): Total records per period.
    • sum('column'): Sum of a numeric column.
    • average('column'): Average of a numeric column.
    • min('column'), max('column'): Extremes of a column.
    • Custom aggregations via aggregate(fn (Builder $query) => ...):
      ->aggregate(fn ($query) => $query->selectRaw('SUM(revenue) as total_revenue'))
      
  4. Date Ranges:

    • Use between(start, end) for explicit ranges.
    • Shortcuts like thisMonth(), lastYear(), or customRange():
      ->between(
          start: now()->startOfMonth(),
          end: now()->endOfMonth()
      )
      
  5. Integration with Charting:

    • Pass the trend result to libraries like chartjs or highcharts:
      return view('dashboard', [
          'trend' => $trend->toArray(),
      ]);
      
    • Use Trend::model(...)->render() (if the package adds this in the future; check updates).
  6. Caching Trends:

    • Cache results for performance (e.g., 5 minutes):
      $trend = Cache::remember('user_trend_monthly', 300, function () {
          return Trend::model(User::class)
              ->between(...)
              ->perMonth()
              ->count();
      });
      

Gotchas and Tips

Pitfalls

  1. Performance on Large Datasets:

    • Avoid perMinute() or perHour() on tables with millions of rows without indexing.
    • Fix: Add database indexes on filtered columns (e.g., name, created_at):
      Schema::table('users', function (Blueprint $table) {
          $table->index('name');
          $table->index('created_at');
      });
      
  2. Time Zone Handling:

    • Trends respect Laravel’s config('app.timezone'). Ensure consistency:
      Trend::model(Order::class)
          ->between(
              start: now('America/New_York')->startOfDay(),
              end: now('America/New_York')->endOfDay()
          )
          ->perDay();
      
  3. Custom Periods and Carbon:

    • Custom periods must return Carbon instances. Invalid inputs (e.g., strings) will throw errors.
    • Debug: Use dd($date) in your custom period closure to verify types.
  4. Aggregation Quirks:

    • average() and sum() require numeric columns. Non-numeric columns (e.g., string) will return null.
    • Fix: Cast columns in the model or use selectRaw():
      ->selectRaw('CAST(weight AS DECIMAL(10,2)) as weight')
      
  5. Empty Results:

    • If no data exists in the range, the trend returns an empty Collection.
    • Workaround: Provide a default value or handle in the view:
      $trend->isEmpty() ? [] : $trend->toArray();
      
  6. Database Compatibility:

    • Some aggregation methods (e.g., min/max on JSON columns) may fail on older MySQL versions.
    • Fix: Use raw queries or update your database.

Debugging Tips

  1. Log Raw Queries: Enable Laravel’s query logging to inspect generated SQL:

    DB::enableQueryLog();
    $trend = Trend::model(User::class)->between(...)->perDay()->count();
    dd(DB::getQueryLog());
    
  2. Test with Small Datasets: Use factory() or seeders to test trends before deploying to production:

    User::factory()->count(100)->create();
    
  3. Check for Deprecations: Monitor the changelog for breaking changes (e.g., method renames).

Extension Points

  1. Custom Aggregators: Extend the package by creating a macro for reusable aggregations:

    Trend::macro('customAggregation', function () {
        return $this->aggregate(fn ($query) => $query->selectRaw('AVG(score) as custom_score'));
    });
    

    Usage:

    Trend::model(User::class)->customAggregation();
    
  2. Add New Time Periods: Create a trait or helper for non-standard periods (e.g., "quarter"):

    Trend::macro('perQuarter', function () {
        return $this->period(fn ($date) => $date->copy()->startOfQuarter());
    });
    
  3. Integrate with Jobs: Offload trend generation to a queue job for long-running queries:

    TrendJob::dispatch(User::class, now()->subYear(), now(), 'perMonth', 'count');
    

    Job class:

    public function handle() {
        $trend = Trend::model($this->model)
            ->between($this->start, $this->end)
            ->{$this->period}()
            ->{$this->aggregation}();
        // Store or cache $trend
    }
    
  4. Localization: Override period labels (e.g., translate "Month" to another language) by extending the Trend class:

    class LocalizedTrend extends Trend {
        public function perMonth() {
            return $this->period(fn ($date) => [
                'period' => $date->translatedFormat('M Y'), // Example: "Ene 2023"
                'date' => $date->startOfMonth(),
            ]);
        }
    }
    
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