Try Live
Add Docs
Rankings
Pricing
Docs
Install
Install
Docs
Pricing
More...
More...
Try Live
Rankings
Enterprise
Create API Key
Add Docs
Charts
https://github.com/consoletvs/charts
Admin
Charts is a PHP (Laravel) library designed to handle all chart creation and management within
...
Tokens:
4,948
Snippets:
20
Trust Score:
9.1
Update:
4 months ago
Context
Skills
Chat
Benchmark
83.1
Suggestions
Latest
Show doc for...
Code
Info
Show Results
Context Summary (auto-generated)
Raw
Copy
Link
# Laravel Charts Laravel Charts is a PHP library for Laravel applications that provides a unified API for creating interactive charts across multiple JavaScript charting libraries. The package abstracts away the complexity of working directly with charting libraries by offering a fluent, expressive PHP interface that generates the necessary JavaScript code. It supports popular charting libraries including Chart.js, Highcharts, ECharts, Frappe Charts, FusionCharts, and C3.js, allowing developers to switch between libraries without rewriting their chart logic. The library features AJAX loading capabilities with customizable loading animations, automatic dataset formatting, responsive sizing, and extensive customization options. It integrates seamlessly with Laravel's service container and Blade templating system, making it straightforward to render charts in views. The package handles data normalization, color management, and provides chainable methods for configuring chart appearance, titles, legends, axes, and more. ## Creating a Basic Chart.js Chart ```php <?php namespace App\Charts; use ConsoleTVs\Charts\Classes\Chartjs\Chart; class SalesChart { public function build() { $chart = new Chart(); $chart->labels(['January', 'February', 'March', 'April', 'May']) ->dataset('Sales 2024', 'line', [65, 59, 80, 81, 56]) ->options([ 'responsive' => true, 'maintainAspectRatio' => false ]) ->height(300) ->width(600); return $chart; } } // In controller: public function index() { $salesChart = (new SalesChart())->build(); return view('dashboard', compact('salesChart')); } // In Blade view (resources/views/dashboard.blade.php): // <div class="chart-container"> // {!! $salesChart->container() !!} // </div> // {!! $salesChart->script() !!} ``` ## Adding Multiple Datasets with Styling ```php <?php use ConsoleTVs\Charts\Classes\Chartjs\Chart; $chart = new Chart(); $chart->labels(['Q1', 'Q2', 'Q3', 'Q4']); // First dataset - line chart $chart->dataset('Revenue', 'line', [15000, 18000, 22000, 25000]) ->color('rgba(54, 162, 235, 1)') ->backgroundColor('rgba(54, 162, 235, 0.2)') ->fill(true) ->lineTension(0.4); // Second dataset - bar chart $chart->dataset('Expenses', 'bar', [12000, 13500, 16000, 18000]) ->color('rgba(255, 99, 132, 1)') ->backgroundColor('rgba(255, 99, 132, 0.6)'); // Third dataset - dashed line $chart->dataset('Target', 'line', [20000, 20000, 20000, 20000]) ->color('rgba(75, 192, 192, 1)') ->backgroundColor('transparent') ->fill(false) ->dashed([5, 5]); $chart->options([ 'scales' => [ 'yAxes' => [ [ 'ticks' => [ 'beginAtZero' => true, 'callback' => "function(value) { return '$' + value.toLocaleString(); }" ] ] ] ] ]); return $chart; ``` ## Creating Charts with AJAX Loading ```php <?php // In routes/web.php: Route::get('/charts/sales-data', 'ChartController@salesData')->name('charts.sales'); // In ChartController: public function index() { $chart = new Chart(); $chart->labels([]) ->load(route('charts.sales')) ->loader(true) ->loaderColor('#3498db') ->height(400); return view('dashboard', compact('chart')); } public function salesData() { $chart = new Chart(); // Fetch data from database $sales = DB::table('sales') ->selectRaw('DATE(created_at) as date, SUM(amount) as total') ->groupBy('date') ->orderBy('date') ->get(); $labels = $sales->pluck('date')->toArray(); $data = $sales->pluck('total')->toArray(); $chart->labels($labels) ->dataset('Daily Sales', 'line', $data) ->color('#2ecc71') ->backgroundColor('rgba(46, 204, 113, 0.1)') ->fill(true); // Return JSON response for AJAX return response()->json([ 'datasets' => json_decode($chart->api()), 'labels' => $labels ]); } ``` ## Customizing Chart Appearance with Titles and Legends ```php <?php use ConsoleTVs\Charts\Classes\Chartjs\Chart; $chart = new Chart(); $chart->labels(['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']) ->dataset('Page Views', 'bar', [1200, 1900, 1500, 2100, 2800, 2200, 1800]) ->backgroundColor([ '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40', '#FF6384' ]); // Add title $chart->title( 'Weekly Page Views Analytics', 16, // font size '#333', // color 'bold', // font weight "'Segoe UI', 'Roboto', 'Arial', sans-serif" // font family ); // Display or hide legend $chart->displayLegend(true); // Display or hide axes $chart->displayAxes(true); // Adjust bar width $chart->barWidth(0.5); // Minimalist mode (hide legend and axes) // $chart->minimalist(true); $chart->height(350); return $chart; ``` ## Using Highcharts Library ```php <?php use ConsoleTVs\Charts\Classes\Highcharts\Chart; $chart = new Chart(); $chart->labels(['Apples', 'Bananas', 'Oranges', 'Mangoes', 'Grapes']) ->dataset('Fruit Sales', 'column', [45, 67, 38, 52, 71]) ->color('#7cb5ec') ->backgroundColor('#90ed7d'); $chart->options([ 'chart' => [ 'type' => 'column' ], 'title' => [ 'text' => 'Monthly Fruit Sales' ], 'xAxis' => [ 'title' => [ 'text' => 'Fruit Types' ] ], 'yAxis' => [ 'title' => [ 'text' => 'Units Sold' ], 'min' => 0 ], 'plotOptions' => [ 'column' => [ 'dataLabels' => [ 'enabled' => true ] ] ] ]); $chart->height(400); // In Blade view: // {!! $chart->container() !!} // <script src="https://code.highcharts.com/highcharts.js"></script> // {!! $chart->script() !!} return $chart; ``` ## Using ECharts Library ```php <?php use ConsoleTVs\Charts\Classes\Echarts\Chart; $chart = new Chart(); $chart->labels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']) ->dataset('Temperature (°C)', 'line', [12, 14, 18, 22, 26, 28]) ->color('#ee6666') ->dataset('Rainfall (mm)', 'bar', [45, 38, 28, 22, 18, 12]) ->color('#5470c6'); // Set theme (default, light, dark) $chart->theme = 'dark'; $chart->options([ 'title' => [ 'text' => 'Weather Statistics', 'left' => 'center' ], 'tooltip' => [ 'trigger' => 'axis', 'axisPointer' => [ 'type' => 'cross' ] ], 'legend' => [ 'data' => ['Temperature (°C)', 'Rainfall (mm)'], 'top' => 'bottom' ], 'grid' => [ 'left' => '3%', 'right' => '4%', 'bottom' => '10%', 'containLabel' => true ] ]); $chart->height(450) ->width(800); // In Blade view: // {!! $chart->container() !!} // <script src="https://cdn.jsdelivr.net/npm/echarts@5/dist/echarts.min.js"></script> // {!! $chart->script() !!} return $chart; ``` ## Working with Laravel Collections ```php <?php use ConsoleTVs\Charts\Classes\Chartjs\Chart; use Illuminate\Support\Collection; // Using Eloquent collections $users = User::selectRaw('DATE(created_at) as date, COUNT(*) as count') ->where('created_at', '>=', now()->subDays(30)) ->groupBy('date') ->orderBy('date') ->get(); $chart = new Chart(); // Collections are automatically converted to arrays $chart->labels($users->pluck('date')) ->dataset('New Users', 'line', $users->pluck('count')) ->color('rgba(75, 192, 192, 1)') ->backgroundColor('rgba(75, 192, 192, 0.2)') ->fill(true); // Using manual collections $categories = collect(['Electronics', 'Clothing', 'Food', 'Books']); $sales = collect([15000, 23000, 18000, 9500]); $chart->labels($categories) ->dataset('Category Sales', 'bar', $sales); $chart->height(300); return $chart; ``` ## Generating Chart Classes with Artisan Command ```bash # Generate a chart class using the default library (Chart.js) php artisan make:chart UserRegistrationChart # Generate a chart class using a specific library php artisan make:chart SalesChart chartjs php artisan make:chart RevenueChart highcharts php artisan make:chart AnalyticsChart echarts # Output: # [Charts] Creating chart... # [Charts] Chart created! - Location: app/Charts/UserRegistrationChart.php ``` ```php <?php // Generated chart class (app/Charts/UserRegistrationChart.php): namespace App\Charts; use ConsoleTVs\Charts\Classes\Chartjs\Chart; class UserRegistrationChart { public function build(): Chart { $chart = new Chart(); // Fetch data from database $registrations = \App\Models\User::selectRaw('DATE(created_at) as date, COUNT(*) as count') ->where('created_at', '>=', now()->subMonth()) ->groupBy('date') ->get(); $chart->labels($registrations->pluck('date')) ->dataset('Registrations', 'line', $registrations->pluck('count')) ->color('#3498db') ->backgroundColor('rgba(52, 152, 219, 0.2)') ->fill(true); $chart->title('User Registrations - Last 30 Days') ->displayLegend(false) ->height(300); return $chart; } } ``` ## Advanced Options with Raw JavaScript ```php <?php use ConsoleTVs\Charts\Classes\Chartjs\Chart; $chart = new Chart(); $chart->labels(['Category A', 'Category B', 'Category C']) ->dataset('Data Series', 'bar', [12, 19, 8]); // Using rawObject() for JavaScript callbacks $chart->options([ 'scales' => [ 'yAxes' => [ [ 'ticks' => [ 'beginAtZero' => true, 'callback' => $chart->rawObject(" function(value, index, values) { return value.toLocaleString('en-US', { style: 'currency', currency: 'USD' }); } ") ] ] ] ], 'tooltips' => [ 'callbacks' => [ 'label' => $chart->rawObject(" function(tooltipItem, data) { var dataset = data.datasets[tooltipItem.datasetIndex]; var value = dataset.data[tooltipItem.index]; return dataset.label + ': $' + value.toLocaleString(); } ") ] ] ]); return $chart; ``` ## Publishing Configuration and Views ```bash # Publish the configuration file php artisan vendor:publish --tag=charts_config # This creates config/charts.php: # return [ # 'default_library' => 'Chartjs', # ]; # Publish views for customization php artisan vendor:publish --provider="ConsoleTVs\Charts\ChartsServiceProvider" # This publishes views to resources/views/vendor/charts/: # - chartjs/container.blade.php # - chartjs/script.blade.php # - highcharts/container.blade.php # - highcharts/script.blade.php # - echarts/container.blade.php # - echarts/script.blade.php # (and others for different libraries) ``` ## Complete Controller Example ```php <?php namespace App\Http\Controllers; use ConsoleTVs\Charts\Classes\Chartjs\Chart; use App\Models\Order; use Illuminate\Http\Request; class DashboardController extends Controller { public function index() { $revenueChart = $this->createRevenueChart(); $orderStatusChart = $this->createOrderStatusChart(); return view('dashboard', compact('revenueChart', 'orderStatusChart')); } private function createRevenueChart() { $data = Order::selectRaw('DATE(created_at) as date, SUM(total) as revenue') ->where('created_at', '>=', now()->subDays(14)) ->groupBy('date') ->orderBy('date') ->get(); $chart = new Chart(); $chart->labels($data->pluck('date')) ->dataset('Revenue', 'line', $data->pluck('revenue')) ->color('#2ecc71') ->backgroundColor('rgba(46, 204, 113, 0.1)') ->fill(true) ->lineTension(0.4); $chart->title('14-Day Revenue Trend', 14, '#333', 'bold') ->height(300) ->options([ 'scales' => [ 'yAxes' => [ [ 'ticks' => [ 'beginAtZero' => true ] ] ] ] ]); return $chart; } private function createOrderStatusChart() { $statusData = Order::selectRaw('status, COUNT(*) as count') ->groupBy('status') ->get(); $chart = new Chart(); $chart->labels($statusData->pluck('status')) ->dataset('Orders by Status', 'doughnut', $statusData->pluck('count')) ->backgroundColor([ '#3498db', '#2ecc71', '#f39c12', '#e74c3c', '#9b59b6' ]); $chart->title('Order Status Distribution') ->height(300) ->displayLegend(true); return $chart; } } ``` ## Summary Laravel Charts provides a comprehensive solution for integrating interactive charts into Laravel applications with minimal effort. The primary use cases include building analytics dashboards, displaying time-series data like sales trends and user growth, creating financial reports with multiple datasets, and visualizing statistical information across various business metrics. The library's fluent API allows developers to chain method calls for configuring datasets, styling, and options, making the code readable and maintainable. It supports real-time data visualization through AJAX endpoints, enabling dynamic chart updates without page refreshes. Integration patterns typically involve creating chart classes or methods in controllers that fetch data from Eloquent models, configure chart instances with the desired library (Chart.js, Highcharts, ECharts, etc.), and pass the chart objects to Blade views. The package handles the JavaScript generation automatically, requiring only the inclusion of container and script outputs in the view templates. For more complex scenarios, developers can publish and customize the view templates, use raw JavaScript objects for advanced callbacks, and leverage Laravel Collections for seamless data transformation. The Artisan command facilitates rapid chart class generation, promoting a consistent structure across the application.