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

Livecharts Laravel Package

matheusmarnt/livecharts

LiveCharts is a reactive chart abstraction for Laravel using a pure PHP fluent API. Build 18 chart types and render via a single Livewire component. Supports ApexCharts and Chart.js with pluggable engines, enabling easy updates without JS boilerplate.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Install the package:

    composer require matheusmarnt/livecharts
    php artisan livecharts:install
    
    • This publishes config, assets, and optionally chart stubs.
  2. Define a chart (e.g., in a controller or Livewire component):

    use Matheusmarnt\LiveCharts\Facades\LiveCharts;
    
    $chart = LiveCharts::line()
        ->title('Monthly Revenue')
        ->labels(['Jan', 'Feb', 'Mar'])
        ->dataset('2026', [100, 200, 150])
        ->colors(['#3B82F6']);
    
  3. Render the chart in a Blade view:

    <livewire:livecharts :chart="$chart" />
    
    • Ensure @liveChartsScripts is placed before @livewireScripts in your layout.

First Use Case

Dynamic Livewire Dashboard:

  • Create a Livewire component with a chart bound to a property.
  • Update the property (e.g., via a button or polling), and the chart reacts instantly.
    public $chartData = [100, 200, 150];
    public function mount() {
        $this->chart = LiveCharts::line()
            ->title('Dynamic Data')
            ->labels(['Jan', 'Feb', 'Mar'])
            ->dataset('Values', $this->chartData);
    }
    public function updateData() {
        $this->chartData = [200, 300, 400];
    }
    

Implementation Patterns

Core Workflows

  1. Fluent Builder Pattern:

    • Chain methods for declarative chart configuration:
      LiveCharts::bar()
          ->title('Sales')
          ->labels(['Q1', 'Q2'])
          ->dataset('North', [100, 200])
          ->dataset('South', [150, 250])
          ->stacked()
          ->height(400);
      
    • Tip: Use ->palette(TwPalette::Vibrant) for auto-colored datasets.
  2. Class-Based Charts:

    • Generate reusable charts with make:chart:
      php artisan make:chart SalesChart --type=bar
      
    • Extend Matheusmarnt\LiveCharts\Charts\Chart and override methods like build():
      class SalesChart extends Chart {
          protected string $type = 'bar';
          public function build() {
              $this->title('Sales Overview');
              $this->labels(['Jan', 'Feb']);
              $this->datasets([
                  Dataset::make('North')->data([100, 200]),
                  Dataset::make('South')->data([150, 250]),
              ]);
          }
      }
      
    • Use Case: Reuse charts across components (e.g., admin dashboards).
  3. Livewire Integration:

    • Bind charts to Livewire properties for reactivity:
      public $chart;
      public function mount() {
          $this->chart = new SalesChart();
      }
      
    • Update data via Livewire methods (e.g., after API calls):
      public function fetchData() {
          $data = Api::fetchSales();
          $this->chart->datasets()->first()->data($data['north']);
      }
      
  4. Polling for Real-Time Updates:

    • Enable polling in the chart:
      $chart->poll(5000); // Refresh every 5 seconds
      
    • Handle updates in Livewire:
      public function refresh() {
          $this->chart->datasets()->first()->data($this->fetchFreshData());
      }
      
    • Blade Event Listener:
      <script>
          window.addEventListener('livecharts:refreshed', (e) => {
              console.log('Chart refreshed:', e.detail.id);
          });
      </script>
      
  5. Event Handling:

    • Map chart events to Livewire methods:
      $chart
          ->onDataPointClick('chartClicked')
          ->onZoom('chartZoomed');
      
    • Define Livewire event handlers:
      #[On('chartClicked')]
      public function handleClick(array $data) {
          $this->emit('alert', 'Clicked: ' . $data['label']);
      }
      
  6. Broadcasting:

    • Push updates via Laravel Echo:
      $chart->broadcastOn('private-charts.user123')->broadcastAs('chart.update');
      
    • Subscribe in JavaScript:
      Echo.channel('private-charts.user123')
          .listen('chart.update', (data) => {
              // Update chart or trigger Livewire method
          });
      

Integration Tips

  • Dark Mode Support: Use theme-aware colors:

    $chart->titleColor(dark: TwColor::Amber300, light: TwColor::Amber600);
    
    • Charts auto-adjust when <html class="dark"> toggles.
  • Multi-Engine: Switch engines globally or per chart:

    LiveCharts::line()->engine('chartjs')->labels(['Jan', 'Feb']);
    
    • Register custom engines:
      LiveCharts::registerEngine('highcharts', HighchartsAdapter::class);
      
  • Asset Management:

    • Local-First: Default (both mode) serves local files with CDN fallback.
    • CDN-Only: Set LIVECHARTS_ASSETS_MODE=cdn in .env to skip asset publishing.
    • Vite Integration: For custom builds, extend the livecharts.js IIFE in resources/js.
  • Stub Customization: Edit stubs/livecharts/chart.stub to modify the boilerplate for make:chart.


Gotchas and Tips

Pitfalls

  1. Missing Assets:

    • Error: ApexCharts is not defined or Chart is not defined.
    • Fix: Run php artisan vendor:publish --tag=livecharts-assets --force to republish assets.
    • Prevention: Always run livecharts:install after composer install.
  2. Asset Strategy Mismatch:

    • Error: Charts fail in SPA mode (wire:navigate) with livecharts is not defined.
    • Fix: Ensure LIVECHARTS_ASSETS_STRATEGY=navigate (default) or manually include @liveChartsScripts before @livewireScripts for stack mode.
  3. Livewire Hydration Issues:

    • Error: Charts render blank after navigation.
    • Fix: Use wire:key on the Livewire component to force remount:
      <livewire:livecharts :chart="$chart" wire:key="chart-{{ $key }}" />
      
  4. Polling Conflicts:

    • Error: Multiple charts with polling cause race conditions.
    • Fix: Use unique wire:poll keys or disable polling for non-critical charts.
  5. Dark Mode Lag:

    • Issue: Charts flicker during dark mode toggle.
    • Fix: Use theme('auto') and ensure the dark:/light: color pairs are defined for all critical elements.
  6. Custom Engine Registration:

    • Error: Custom engine not recognized.
    • Fix: Verify the adapter implements Matheusmarnt\LiveCharts\Contracts\EngineAdapter and is registered before use:
      LiveCharts::registerEngine('my-engine', MyAdapter::class);
      

Debugging Tips

  • Inspect Rendered JSON: Add {{ dd($chart->toJson()) }} to debug chart configuration before rendering.

  • Check Console for Errors: Open browser dev tools to catch missing assets or JS errors (e.g., livecharts is not defined).

  • Preview All Chart Types: Use php artisan livecharts:preview to test every chart type in isolation.

  • Livewire Logs: Enable Livewire logging in config/livewire.php to debug hydration issues:

    'log' => env('LIVEWIRE_LOG', false),
    

Extension Points

  1. Custom Chart Types:

    • Extend the generic factory:
      LiveCharts::make('custom')
          ->engine('apexcharts')
          ->config(['chart' => ['type' => 'custom']]);
      
  2. Theme Extensions:

    • Add custom TwColor or TwPalette values by extending the enums in config/livecharts.php:
      'colors' => [
          'custom' => ['#FF00FF', '#00FFFF'],
      ],
      
  3. Event Augmentation:

    • Extend event handling by overriding the handleEvent() method in a custom chart class.
  4. Asset Overrides:

    • Replace engine bundles by publishing custom files to `public/vendor
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity