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

Filament Simple Stats Laravel Package

spatie/filament-simple-stats

Opinionated, prebuilt stat widgets for Filament dashboards. Quickly add daily counts and sums using Flowframe/laravel-trend, with helpers like last 30 days to generate clean, consistent stats cards with minimal setup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/filament-simple-stats
    

    Ensure your project uses Filament v2+ and Laravel 10+ (or newer, as per changelog).

  2. First Widget: Create a Filament widget (e.g., app/Filament/Widgets/StatsOverview.php):

    use Spatie\FilamentSimpleStats\SimpleStat;
    use Filament\Widgets\Widget;
    
    class StatsOverview extends Widget
    {
        protected function getStats(): array
        {
            return [
                SimpleStat::make('Users')->model(\App\Models\User::class)->count(),
                SimpleStat::make('Revenue')->model(\App\Models\Order::class)->sum('amount'),
            ];
        }
    }
    
  3. Register the Widget: Add it to your Filament dashboard in app/Providers/Filament/AdminPanelProvider.php:

    public function panel(Panel $panel): Panel
    {
        return $panel
            ->widgets([
                \App\Filament\Widgets\StatsOverview::class,
            ]);
    }
    

First Use Case: Quick Metrics Dashboard

Use SimpleStat to display real-time counts/sums with minimal code:

SimpleStat::make('Active Users')
    ->model(\App\Models\User::class)
    ->where('active', true)
    ->count()
    ->description('Last 7 days')
    ->last7Days();

Implementation Patterns

Core Workflows

  1. Model-Based Stats:

    SimpleStat::make('Orders')
        ->model(\App\Models\Order::class)
        ->last30Days()
        ->dailySum('total'); // Sums 'total' column daily
    
  2. Query Customization:

    SimpleStat::make('High-Value Users')
        ->model(\App\Models\User::class)
        ->where('lifetime_value', '>', 1000)
        ->count();
    
  3. Trend Analysis:

    SimpleStat::make('Monthly Revenue')
        ->model(\App\Models\Order::class)
        ->last12Months()
        ->monthlySum('amount')
        ->description('YoY Growth');
    

Integration Tips

  1. Dynamic Data: Use closures for runtime conditions (e.g., user-specific stats):

    SimpleStat::make('My Orders')
        ->model(\App\Models\Order::class)
        ->where(fn ($query) => $query->where('user_id', auth()->id()))
        ->count();
    
  2. Custom Aggregations: Extend with raw SQL or custom Eloquent queries:

    SimpleStat::make('Avg. Order Value')
        ->query(\App\Models\Order::query()->avg('amount'))
        ->withoutTrend();
    
  3. Conditional Rendering: Hide stats based on permissions or data availability:

    protected function getStats(): array
    {
        return auth()->user()->can('view_analytics')
            ? [SimpleStat::make('Analytics')->model(...)]
            : [];
    }
    

Advanced Patterns

  1. Nested Stats: Combine with Filament’s Stat for custom formatting:

    use Filament\Widgets\StatsOverviewWidget\Stat;
    
    Stat::make('Users', User::count())
        ->description('Total')
        ->chart([...]);
    
  2. Time-Based Segmentation: Use lastNDays(), lastNMonths(), or between() for granular trends:

    SimpleStat::make('Q1 Revenue')
        ->model(\App\Models\Order::class)
        ->between('2024-01-01', '2024-03-31')
        ->sum('amount');
    
  3. Multi-Model Aggregations: Join tables for cross-model stats:

    SimpleStat::make('User Orders')
        ->query(\App\Models\Order::query()
            ->selectRaw('user_id, count(*) as orders')
            ->groupBy('user_id'))
        ->sum('orders');
    

Gotchas and Tips

Pitfalls

  1. Performance:

    • Issue: Heavy queries (e.g., last30Days()->dailySum()) on large tables may slow dashboards.
    • Fix: Cache results with cache() or use database indexes:
      SimpleStat::make('Users')->cache(fn () => User::count(), now()->addHours(1));
      
  2. Trend Accuracy:

    • Issue: withoutTrend() disables all trend calculations, which may mislead users.
    • Fix: Use invertTrendColors() for metrics where decreases are positive (e.g., errors).
  3. Time Zone Mismatches:

    • Issue: lastNDays() uses the server’s timezone. Client-side dashboards may show stale data.
    • Fix: Explicitly set timezone in queries:
      SimpleStat::make('Users')->model(User::class)
          ->whereDate('created_at', '>=', now()->timezone('UTC')->subDays(7));
      

Debugging

  1. Query Inspection: Use toSql() to debug queries:

    $query = SimpleStat::make('Users')->model(User::class)->count()->getQuery();
    dd($query->toSql(), $query->getBindings());
    
  2. Trend Calculation: Verify trend logic by inspecting the underlying Trend model:

    $stat = SimpleStat::make('Users')->last7Days()->count();
    dd($stat->getTrendData()); // Check raw trend values
    

Extension Points

  1. Custom Stat Classes: Extend SimpleStat for reusable logic:

    class UserStat extends SimpleStat
    {
        public function activeCount(): self
        {
            return $this->where('active', true)->count();
        }
    }
    
  2. Override Defaults: Modify trend colors or icons via Filament’s theme:

    // config/filament.php
    'colors' => [
        'success' => '#10b981', // Custom green for trends
    ];
    
  3. Localization: Translate stat labels dynamically:

    SimpleStat::make(__('Users'))->model(User::class)->count();
    

Pro Tips

  1. A/B Testing: Use withoutTrend() for control groups to test impact of trend visuals.

  2. Dark Mode: Ensure trend icons/colors are visible in dark mode by overriding Filament’s CSS:

    .filament-widgets-stat-trend--down {
        color: #ef4444; /* Red for dark mode */
    }
    
  3. Accessibility: Add aria-label for screen readers:

    SimpleStat::make('Users')->model(User::class)
        ->count()
        ->description('Total active users')
        ->extraAttributes(['aria-label' => 'Active user count']);
    
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