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 Steps

  1. Installation:

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

    Register the plugin in your Panel configuration:

    use Leandrocfe\FilamentApexCharts\FilamentApexChartsPlugin;
    public function panel(Panel $panel): Panel {
        return $panel->plugins([FilamentApexChartsPlugin::make()]);
    }
    
  2. Generate a Chart Widget:

    php artisan make:filament-apex-charts BlogPostsChart
    

    This creates a BlogPostsChart.php file in app/Filament/Widgets/ with a basic bar chart configuration.

  3. First Use Case:

    • Open the generated widget file and modify the getOptions() method to customize the chart (e.g., change chart type, data, or styling).
    • Example: Replace ApexChartTypeEnum::Bar with ApexChartTypeEnum::Line for a line chart.
    • Save the file and refresh your Filament dashboard to see the updated chart.

Where to Look First


Implementation Patterns

Usage Patterns

  1. Chart Types: Use the ApexChartTypeEnum to define chart types (e.g., ApexChartTypeEnum::Pie, ApexChartTypeEnum::Donut). Example:

    'chart' => [
        'type' => ApexChartTypeEnum::Pie,
        'height' => 350,
    ],
    
  2. Dynamic Data: Fetch data dynamically in getOptions() using Eloquent or API calls. Example:

    protected function getOptions(): array {
        $data = Post::query()->selectRaw('MONTH(created_at) as month, COUNT(*) as count')
            ->groupBy('month')
            ->pluck('count', 'month')
            ->toArray();
        return [
            'series' => [['data' => $data]],
            'xaxis' => ['categories' => array_keys($data)],
        ];
    }
    
  3. Reusable Components: Extend ApexChartWidget for shared functionality. Example:

    class BaseSalesChart extends ApexChartWidget {
        protected static ?string $chartId = 'baseSalesChart';
        protected static ?int $contentHeight = 300;
    }
    

    Then extend it for specific charts:

    class MonthlySalesChart extends BaseSalesChart {
        protected function getOptions(): array { ... }
    }
    
  4. Filter Integration: Use HasFiltersSchema trait to add interactive filters. Example:

    use Filament\Schemas\Schema;
    use Filament\Forms\Components\Select;
    
    public function filtersSchema(Schema $schema): Schema {
        return $schema->components([
            Select::make('period')
                ->options(['monthly' => 'Monthly', 'yearly' => 'Yearly'])
                ->default('monthly'),
        ]);
    }
    
    public function updatedInteractsWithSchemas(string $statePath): void {
        $this->updateOptions();
    }
    
  5. Real-Time Updates: Leverage polling for live data. Example:

    protected static ?string $pollingInterval = '15s';
    

    Or disable polling:

    protected static ?string $pollingInterval = null;
    

Workflows

  1. Dashboard Integration: Add the widget to your dashboard by including it in the getWidgets() method of your dashboard class:

    protected function getWidgets(): array {
        return [
            BlogPostsChart::class,
            MonthlySalesChart::class,
        ];
    }
    
  2. Resource Pages: Embed charts in resource pages using Widget:

    public static function getWidgets(): array {
        return [
            Widgets\SalesOverviewChart::class,
        ];
    }
    
  3. Custom Views: Use Blade views for complex footers or loading indicators. Example:

    protected function getFooter(): View {
        return view('filament.widgets.custom-footer', ['data' => $this->getChartData()]);
    }
    

Integration Tips

  • Theme Consistency: Use the theme option in getOptions() to match Filament’s dark/light mode:

    'theme' => [
        'mode' => Filament::getCurrentPanel()?->darkMode() ? 'dark' : 'light',
    ],
    
  • Performance: For large datasets, use deferLoading to avoid blocking page load:

    protected static bool $deferLoading = true;
    
  • Localization: Publish translations to customize labels:

    php artisan vendor:publish --tag=filament-apex-charts-translations
    
  • Testing: Test chart rendering with:

    php artisan test
    

    Mock data in tests to avoid database dependencies.


Gotchas and Tips

Pitfalls

  1. Chart Not Rendering:

    • Cause: Missing getOptions() method or empty return array.
    • Fix: Ensure getOptions() returns a valid ApexCharts configuration. Example:
      return [
          'chart' => ['type' => ApexChartTypeEnum::Line],
          'series' => [['data' => [1, 2, 3]]],
      ];
      
  2. Filter Data Not Updating:

    • Cause: Forgetting to call updateOptions() in updatedInteractsWithSchemas().
    • Fix: Always update chart options after filter changes:
      public function updatedInteractsWithSchemas(string $statePath): void {
          $this->updateOptions();
      }
      
  3. Polling Conflicts:

    • Cause: Multiple widgets with the same $pollingInterval causing rapid API calls.
    • Fix: Use unique intervals or disable polling for non-real-time charts.
  4. Dark Mode Issues:

    • Cause: Custom CSS overriding ApexCharts dark mode styles.
    • Fix: Use ApexCharts’ built-in dark mode or override styles with !important sparingly.
  5. Z-Index Problems:

    • Cause: Filament dropdowns or modals overlapping charts.
    • Fix: Increase the chart’s z-index in extraJsOptions():
      protected function extraJsOptions(): ?RawJs {
          return RawJs::make('{ "chart": { "foreColor": "#fff", "zIndex": 1000 } }');
      }
      

Debugging

  1. Console Errors: Check browser console for ApexCharts errors (e.g., missing data or invalid options). Use console.log in extraJsOptions() for debugging:

    protected function extraJsOptions(): ?RawJs {
        return RawJs::make(<<<'JS'
        {
            chart: {
                events: {
                    mounted: function(ctx) { console.log("Chart mounted", ctx); }
                }
            }
        }
        JS);
    }
    
  2. Network Requests: Use browser dev tools to inspect API responses for dynamic data. Ensure CORS headers are set if fetching from external APIs.

  3. Filament Logs: Enable Filament’s debug mode in .env:

    FILAMENT_DEBUG=true
    

    Check logs for widget initialization errors.

Tips

  1. Reusable Options: Extract common chart options into a trait or base class to avoid repetition:

    trait CommonChartOptions {
        protected function getCommonOptions(): array {
            return [
                'colors' => ['#3b82f6', '#10b981'],
                'stroke' => ['width' => 2],
                'markers' => ['size' => 4],
            ];
        }
    }
    
  2. Responsive Design: Use ApexCharts’ responsive options to ensure charts adapt to screen size:

    'chart' => [
        'type' => ApexChartTypeEnum::Line,
        'height' => '100%',
        'width' => '100%',
    ],
    'responsive' => [
        'end' => [100, 150],
    ],
    
  3. Custom Tooltips: Enhance interactivity with custom tooltips:

    'tooltip' => [
        'custom' => function({ value, seriesIndex, dataPointIndex, w }) {
            return `<div class="filament-apex-tooltip">
                <span>${w.config.series[seriesIndex].name}</span>
                <span>${value} units</span>
            </div>`;
        },
    ],
    
  4. Animation Control:

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.
bugban/symfony
beyonder-capi/workflow-extensions-bundle
beyonder-capi/job-queue-bundle
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
22h/doctrine-garbage-collection-bundle
agtp/agtp-php
agtp/mod-php
splash/sonata-admin