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 Apex Charts Laravel Package

leandrocfe/filament-apex-charts

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package

    composer require leandrocfe/filament-apex-charts:"^5.0"
    

    Ensure compatibility with your Filament version (v3/v4/v5) by checking the README branches.

  2. Register the Plugin Add to your Panel provider (e.g., app/Providers/Filament/AdminPanelProvider.php):

    public function panel(Panel $panel): Panel {
        return $panel->plugins([
            FilamentApexChartsPlugin::make(),
        ]);
    }
    
  3. Generate a Basic Chart Create a widget with the Artisan command:

    php artisan make:filament-apex-charts BlogPostsChart
    

    This scaffolds a BlogPostsChart class in app/Filament/Widgets/BlogPostsChart.php.

  4. First Render Add the widget to a dashboard or page:

    use App\Filament\Widgets\BlogPostsChart;
    
    public function getWidgets(): array {
        return [
            BlogPostsChart::class,
        ];
    }
    

First Use Case: Simple Line Chart

Edit the generated widget (BlogPostsChart.php) to define a line chart:

use Leandrocfe\FilamentApexCharts\Contracts\HasApexCharts;
use Leandrocfe\FilamentApexCharts\Contracts\HasApexChartsOptions;
use Leandrocfe\FilamentApexCharts\Contracts\HasApexChartsData;

class BlogPostsChart extends Widget implements HasApexCharts, HasApexChartsOptions, HasApexChartsData {
    protected static string $view = 'filament-apex-charts::widget';

    public function getChartType(): string {
        return 'line'; // Chart type
    }

    public function getChartOptions(): array {
        return [
            'chart' => [
                'id' => 'blog-posts-chart',
                'type' => 'line',
                'height' => 350,
            ],
            'stroke' => ['width' => 5],
        ];
    }

    public function getChartData(): array {
        return [
            'labels' => ['Jan', 'Feb', 'Mar', 'Apr'],
            'series' => [
                ['name' => 'Posts', 'data' => [30, 40, 35, 50]],
            ],
        ];
    }
}

Result: A responsive line chart displaying monthly blog post counts.


Implementation Patterns

1. Dynamic Data Binding

Use Eloquent queries or services to fetch real-time data:

public function getChartData(): array {
    $posts = Post::query()
        ->selectRaw('DATE_FORMAT(created_at, "%b") as month')
        ->selectRaw('COUNT(*) as count')
        ->groupBy('month')
        ->orderBy('month')
        ->get();

    return [
        'labels' => $posts->pluck('month'),
        'series' => [
            ['name' => 'Posts', 'data' => $posts->pluck('count')],
        ],
    ];
}

2. Reusable Chart Components

Extract chart logic into a trait or service for consistency:

// app/Services/ApexChartService.php
class ApexChartService {
    public static function buildSalesChart(Collection $data): array {
        return [
            'labels' => $data->pluck('month'),
            'series' => [
                ['name' => 'Sales', 'data' => $data->pluck('revenue')],
            ],
        ];
    }
}

// Usage in widget:
public function getChartData(): array {
    $sales = SalesReport::fetchMonthlyData();
    return ApexChartService::buildSalesChart($sales);
}

3. Interactive Features

Leverage ApexCharts options for tooltips, zoom, and annotations:

public function getChartOptions(): array {
    return [
        'chart' => [
            'zoom' => ['enabled' => true],
            'toolbar' => ['show' => true],
        ],
        'tooltip' => ['y' => ['formatter' => 'function(val) { return "$" + val }']],
    ];
}

4. Multi-Series Charts

Combine multiple data series (e.g., line + column):

public function getChartType(): string {
    return 'mixed'; // Mixed chart type
}

public function getChartData(): array {
    return [
        'labels' => ['Q1', 'Q2', 'Q3'],
        'series' => [
            ['name' => 'Revenue', 'type' => 'column', 'data' => [4500, 5000, 4100]],
            ['name' => 'Expenses', 'type' => 'line', 'data' => [3900, 4500, 4300]],
        ],
    ];
}

5. Integration with Filament Tables

Use chart data from a Filament table’s query:

// In a Filament Table's column:
use Leandrocfe\FilamentApexCharts\Widgets\ApexChartsWidget;

public function getTableWidgets(): array {
    return [
        ApexChartsWidget::make()
            ->query($this->getTableQuery())
            ->chartType('bar')
            ->options([
                'chart' => ['height' => 300],
            ])
            ->data([
                'labels' => $this->getTableQuery()->pluck('month'),
                'series' => [
                    ['name' => 'Metrics', 'data' => $this->getTableQuery()->pluck('value')],
                ],
            ]),
    ];
}

6. Theming and Dark Mode

Extend default styles via CSS or Filament’s asset pipeline:

// In a widget's view (e.g., resources/views/filament/widgets/blog-posts-chart.blade.php)
@push('filament-apex-charts-styles')
    <style>
        .apexcharts-dark .apexcharts-xaxis-label {
            color: #ccc !important;
        }
    </style>
@endpush

Gotchas and Tips

Common Pitfalls

  1. Version Mismatches

    • Issue: Using filament-apex-charts@^5.0 with Filament v2.
    • Fix: Pin to the correct branch (e.g., leandrocfe/filament-apex-charts:v2.0.2).
    • Check: Package branches.
  2. Data Format Errors

    • Issue: ApexCharts expects labels and series in specific formats. Undefined keys or mismatched lengths break rendering.
    • Debug: Use dd($this->getChartData()) to validate structure:
      // Correct:
      ['labels' => ['Jan', 'Feb'], 'series' => [['data' => [10, 20]]]]
      // Incorrect:
      ['labels' => ['Jan'], 'series' => [['data' => [10, 20, 30]]]] // Length mismatch!
      
  3. Asset Loading Conflicts

    • Issue: ApexCharts JS/CSS fails to load due to Filament’s asset pipeline.
    • Fix: Ensure the plugin is registered before other assets are compiled:
      // app/Providers/AppServiceProvider.php
      public function boot() {
          FilamentApexChartsPlugin::make()->register();
      }
      
  4. Dynamic Updates Not Triggering

    • Issue: Real-time data updates (e.g., via Laravel Echo) don’t refresh the chart.
    • Fix: Use ApexCharts’ updateOptions or updateSeries methods via JavaScript:
      // In a widget's view
      <script>
          document.addEventListener('chart-update', function() {
              const chart = document.querySelector('#blog-posts-chart').apexChart;
              chart.updateSeries([{data: [10, 20, 30]}]);
          });
      </script>
      

Debugging Tips

  1. Inspect Rendered HTML Open browser dev tools (F12) and check if the chart container exists:

    <div id="blog-posts-chart" class="apexcharts-chart"></div>
    
    • If missing, verify the widget’s view is correctly referenced ($view property).
  2. Check Console for Errors Look for apexcharts.min.js errors (e.g., missing dependencies):

    Uncaught TypeError: document.querySelector(...).apexChart is undefined
    
    • Solution: Ensure filament-apex-charts::script is included in the layout.
  3. Validate Chart Options Use ApexCharts’ online config validator to test options.


Extension Points

  1. Custom Chart Types Extend the package by creating a new widget class:
    class CustomGaugeChart
    
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware