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

Laravel Chartjs Laravel Package

vitopedro/laravel-chartjs

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require vitopedro/laravel-chartjs
    
  2. Register Service Provider in config/app.php:

    vitopedro\chartjs\ChartjsServiceProvider::class,
    
  3. Publish Assets:

    php artisan vendor:publish --tag=public --force
    

    (Ensures Chart.js JS/CSS files are available in public/vitopedro/chartjs.)

  4. Include Chart.js in Blade: Add to your layout file (e.g., resources/views/layouts/app.blade.php):

    <script src="{{ asset('vitopedro/chartjs/chart.min.js') }}"></script>
    

First Use Case: Basic Line Chart

use vitopedro\chartjs\Chartjs;

// In a controller or Blade file:
$chart = Chartjs::line()
    ->title("Monthly Sales")
    ->labels(["Jan", "Feb", "Mar"])
    ->values([10, 20, 30])
    ->options(['responsive' => true]);

return view('chart', compact('chart'));

Blade Rendering:

<div class="chart-container">
    {!! $chart->render() !!}
</div>

Implementation Patterns

Core Workflows

  1. Dynamic Data Binding: Fetch data from Eloquent models or APIs, then pass to charts:

    $sales = Sales::selectRaw('MONTH(created_at) as month, SUM(amount) as total')
        ->groupBy('month')
        ->get();
    
    $labels = $sales->pluck('month');
    $values = $sales->pluck('total');
    
    $chart = Chartjs::bar()
        ->title("Monthly Revenue")
        ->labels($labels->toArray())
        ->values($values->toArray());
    
  2. Reusable Chart Components: Create a dedicated service class for charts:

    // app/Services/ChartService.php
    class ChartService {
        public function salesChart() {
            return Chartjs::line()
                ->title("Sales Trend")
                ->labels($this->getMonths())
                ->values($this->getSalesData());
        }
    }
    
  3. Blade Directives (Advanced): Register a Blade directive to auto-render charts:

    // In a service provider
    Blade::directive('chart', function ($expression) {
        return "<?php echo {$expression}->render(); ?>";
    });
    

    Usage:

    @chart($chart)
    
  4. API-Driven Charts: Return chart data as JSON for frontend frameworks (Vue/React):

    return response()->json([
        'labels' => $labels,
        'values' => $values,
        'type'   => 'line'
    ]);
    

Integration Tips

  • Laravel Mix/Webpack: Ensure Chart.js is included via Mix (if not using published assets):

    // resources/js/app.js
    import 'chart.js';
    
  • Livewire/Alpine.js: Combine with Livewire for dynamic updates:

    // Livewire component
    public function render() {
        $chart = Chartjs::line()
            ->labels($this->getDynamicLabels())
            ->values($this->getDynamicValues());
    
        return view('livewire.chart', ['chart' => $chart]);
    }
    
  • Caching: Cache chart configurations for performance:

    $chartConfig = Cache::remember('chart-config', 3600, function() {
        return Chartjs::line()->labels($labels)->values($values);
    });
    

Gotchas and Tips

Pitfalls

  1. Asset Paths:

    • Forgetting to publish assets (vendor:publish) will break JS/CSS loading.
    • Fix: Always run php artisan vendor:publish --tag=public --force after installation.
  2. Chart.js Version Mismatch:

    • The wrapper may not support the latest Chart.js features.
    • Fix: Check the Chart.js changelog and update the package or fork it.
  3. Blade Escaping:

    • render() outputs raw HTML/JS, which may cause XSS warnings in Blade.
    • Fix: Use {!! $chart->render() !!} or escape manually if needed.
  4. Dynamic Data Types:

    • Passing non-array data (e.g., labels()) will throw errors.
    • Fix: Ensure inputs are arrays:
      ->labels(array_values($labels->toArray()))
      

Debugging

  • Console Errors: Check browser console for missing assets or JS errors (e.g., chart.min.js 404).

    • Debug Tip: Verify the asset path in public/vitopedro/chartjs.
  • Configuration Overrides: The package may not support all Chart.js options. Refer to the Chart.js docs for unsupported options.

    • Workaround: Extend the package or use raw JS for custom configurations.

Extension Points

  1. Custom Chart Types: Extend the base class to add new chart types (e.g., Doughnut):

    // app/Extensions/CustomChart.php
    use vitopedro\chartjs\Chartjs;
    
    class CustomChart extends Chartjs {
        public function doughnut() {
            return $this->setType('doughnut');
        }
    }
    
  2. Plugin Integration: Use Chart.js plugins (e.g., chartjs-plugin-zoom):

    $chart = Chartjs::line()
        ->options([
            'plugins' => [
                'zoom' => ['zoom' => ['wheel' => true, 'mode' => 'xy']]
            ]
        ]);
    
  3. Localization: Override labels/values for non-English apps:

    $chart = Chartjs::line()
        ->labels(__('chart.labels'))
        ->values(__('chart.values'));
    

Performance Tips

  • Lazy Loading: Load Chart.js only on pages with charts using Alpine.js:

    <div x-data="{ loadChart: false }" x-init="loadChart = true">
        @if($loadChart)
            <script src="{{ asset('vitopedro/chartjs/chart.min.js') }}"></script>
            {!! $chart->render() !!}
        @endif
    </div>
    
  • Minify Assets: Use Laravel Mix to minify Chart.js:

    // webpack.mix.js
    mix.js('resources/js/chartjs.min.js', 'public/js')
        .copy('node_modules/chart.js/dist/Chart.min.js', 'public/js/chart.min.js');
    
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.
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium