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

Highcharts Bundle Laravel Package

ob/highcharts-bundle

Symfony bundle that simplifies using Highcharts by generating chart configuration in PHP and rendering via Twig extensions. Build rich, interactive graphs with less JS and DRY chart code. Note: Highcharts requires a commercial license for commercial use.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup in Laravel

  1. Install via Composer (fork or create a wrapper package):

    composer require marcaube/ob-highcharts-bundle
    

    Note: Since this is a Symfony bundle, create a Laravel-compatible package by extracting core classes (Series, Options, Chart) into a new package (e.g., laravel-highcharts).

  2. Extract Core Classes: Copy these files from the bundle to your Laravel project:

    • src/Ob/HighchartsBundle/Chart/Series.php
    • src/Ob/HighchartsBundle/Chart/Options.php
    • src/Ob/HighchartsBundle/Chart/Chart.php Place them in app/Highcharts/ or a new vendor/laravel-highcharts/src/ directory.
  3. Register Autoloading: Add to composer.json:

    "autoload": {
        "psr-4": {
            "App\\Highcharts\\": "app/Highcharts/",
            "LaravelHighcharts\\": "vendor/laravel-highcharts/src/"
        }
    }
    

    Run composer dump-autoload.

  4. Publish Highcharts Assets: Download Highcharts JS/CSS from their site and place in:

    public/vendor/highcharts/
    

    Or use a CDN:

    <script src="https://code.highcharts.com/highcharts.js"></script>
    
  5. First Chart in Blade: Create a simple line chart in a controller:

    // app/Http/Controllers/ChartController.php
    use App\Highcharts\Chart;
    use App\Highcharts\Series;
    use App\Highcharts\Options;
    
    public function showChart() {
        $chart = new Chart();
        $chart->setTitle('Monthly Visits')
              ->setType('line');
    
        $series = new Series();
        $series->setName('Traffic')
               ->setData([1, 2, 3, 4, 5]);
    
        $chart->addSeries($series);
        return view('charts.example', ['chart' => $chart]);
    }
    

    Render in Blade (resources/views/charts/example.blade.php):

    <div id="container" style="height: 400px;"></div>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            Highcharts.chart('container', @json($chart->getConfig()));
        });
    </script>
    

Implementation Patterns

1. Reusable Chart Definitions

Pattern: Define chart configurations as PHP classes for reuse across controllers/views. Example:

// app/Highcharts/Definitions/UserActivityChart.php
namespace App\Highcharts\Definitions;

use App\Highcharts\Chart;
use App\Highcharts\Series;

class UserActivityChart extends Chart {
    public function __construct($data) {
        $this->setTitle('User Activity')
              ->setType('spline')
              ->setXAxis(['categories' => ['Jan', 'Feb', 'Mar']]);

        $series = new Series();
        $series->setName('Active Users')
               ->setData($data);

        $this->addSeries($series);
    }
}

Usage in Controller:

$chart = new UserActivityChart([100, 200, 150]);
return view('dashboard', ['chart' => $chart]);

2. Dynamic Data Binding

Pattern: Fetch data from Eloquent and bind it to charts dynamically. Example:

// Controller
public function salesChart() {
    $sales = Sales::selectRaw('DATE(created_at) as date, SUM(amount) as total')
                  ->groupBy('date')
                  ->pluck('total', 'date')
                  ->toArray();

    $chart = new Chart();
    $chart->setTitle('Monthly Sales')
          ->setType('column');

    $series = new Series();
    $series->setName('Revenue')
           ->setData(array_values($sales));

    $chart->addSeries($series)
          ->setXAxis(['categories' => array_keys($sales)]);

    return view('reports.sales', ['chart' => $chart]);
}

3. Twig-Like Blade Directives (Custom)

Pattern: Create Blade directives to mimic Twig syntax (optional). Register in AppServiceProvider:

use Illuminate\Support\Facades\Blade;

Blade::directive('highchart', function ($expression) {
    return "<?php echo app('highcharts')->chart($expression)->render(); ?>";
});

Usage in Blade:

@highchart($chart)

4. API-Driven Charts

Pattern: Fetch chart data via API endpoints and update dynamically. Controller:

public function getChartData() {
    $data = Analytics::getWeeklyData();
    return response()->json($data);
}

JavaScript (Blade):

<script>
    fetch('/api/chart-data')
        .then(response => response.json())
        .then(data => {
            const chart = Highcharts.chart('container', {
                series: [{
                    data: data.series
                }]
            });
        });
</script>

5. Chart Theming

Pattern: Extend Options class to apply consistent themes. Example:

// app/Highcharts/Themes/DarkTheme.php
namespace App\Highcharts\Themes;

use App\Highcharts\Options;

class DarkTheme extends Options {
    public function __construct() {
        $this->setChart(['backgroundColor' => '#333'])
              ->setTitle(['style' => ['color' => '#fff']])
              ->setPlotOptions(['series' => ['color' => '#fff']]);
    }
}

Usage:

$chart = new Chart();
$chart->applyTheme(new DarkTheme());

6. Event-Driven Customization

Pattern: Use Laravel events to modify charts globally. Example:

// app/Providers/EventServiceProvider.php
protected $listen = [
    'highcharts.build' => [
        'App\Listeners\AddGlobalTooltip',
    ],
];

Listener:

// app/Listeners/AddGlobalTooltip.php
public function handle($event) {
    $event->chart->getOptions()->setTooltip(['shared' => true]);
}

Gotchas and Tips

Pitfalls

  1. Twig Dependency:

    • Issue: The bundle relies on Twig extensions (e.g., {% highcharts_chart %}).
    • Fix: Replace with Blade directives or PHP-based rendering ($chart->render()).
    • Workaround: Use a hybrid approach with PHP-generated JSON:
      <script>
          const config = @json($chart->getConfig());
          Highcharts.chart('container', config);
      </script>
      
  2. Highcharts Licensing:

    • Issue: Highcharts requires a commercial license for non-commercial projects exceeding limits.
    • Fix: Verify licensing terms early. For open-source projects, use the free tier or alternatives like Chart.js.
  3. Asset Loading:

    • Issue: Highcharts JS/CSS must be manually included in Laravel.
    • Fix: Use Laravel Mix/Vite to bundle assets:
      // resources/js/app.js
      import Highcharts from 'highcharts';
      window.Highcharts = Highcharts;
      
      <script src="{{ mix('js/app.js') }}"></script>
      
  4. Deprecated Highcharts Version:

    • Issue: The bundle uses Highcharts v4.0 (2015). Modern features (e.g., stock charts, accessibility) may require upgrades.
    • Fix: Fork the bundle or create a new package with Highcharts v10+:
      npm install highcharts@latest
      
  5. Symfony-Specific Features:

    • Issue: ContainerAware and EventDispatcher won’t work in Laravel.
    • Fix: Replace with Laravel’s ServiceProvider or standalone implementations:
      // Replace ContainerAware with Laravel's Container
      $this->container = app();
      
  6. Dynamic Data Binding:

    • Issue: Directly binding Eloquent collections to Series may cause serialization errors.
    • Fix: Convert data to arrays explicitly:
      $series->setData($collection->pluck('value')->toArray());
      

Debugging Tips

  1. Inspect Chart Config: Dump the raw config to debug:

    dd($chart->getConfig());
    
  2. Highcharts Console: Enable Highcharts’ built-in console for errors:

    Highcharts.setOptions({
        debug: true
    });
    
  3. Blade Debugging: For custom directives, use:

    @dump($chart->getConfig())
    
  4. Asset Paths: Ensure Highcharts JS is loaded before rendering:

    @vite(['
    
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.
yandex/translate-api
voku/simple_html_dom
league/flysystem-vfs
bkwld/upchuck
filament/spatie-laravel-tags-plugin
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