Hi there! If you're working with Laravel 12 and want to add beautiful, interactive charts to your application, this guide is for you. In this beginner-friendly tutorial, I’ll show you how to integrate ChartJS, a popular JavaScript charting library, into Laravel 12.
We’ll create a simple bar chart to visualize sample data, but you can adapt this to display any data from your database.
ChartJS is an open-source JavaScript library that allows you to create responsive, customizable charts like bar, line, pie, and more. It’s lightweight, easy to use, and integrates seamlessly with Laravel for data visualization.
Before we start, ensure you have:
If you don’t have a project, create one with:
laravel new example-app
If you already have a Laravel 12 project, skip this step. Otherwise, run:
laravel new example-app
Navigate to your project directory:
cd example-app
ChartJS can be included via a CDN or installed via npm. For simplicity, we’ll use the CDN to quickly set up the chart. No additional packages are needed for this basic example.
Let’s define a route to display the chart. Open routes/web.php
and add:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChartController;
Route::get('/chart', [ChartController::class, 'index'])->name('chart.index');
This route points to an index
method in a ChartController
we’ll create next.
Run the following command to create a controller:
php artisan make:controller ChartController
Open app/Http/Controllers/ChartController.php
and add the following code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ChartController extends Controller
{
public function index()
{
// Sample data for the chart
$data = [
'labels' => ['January', 'February', 'March', 'April', 'May'],
'values' => [65, 59, 80, 81, 56],
];
return view('chart', compact('data'));
}
}
Explanation:
index
method prepares sample data (labels and values) for the chart.chart
Blade view we’ll create next.Note: In a real application, you’d fetch this data from a database (e.g., using Eloquent models). For example:
$usersPerMonth = User::selectRaw('MONTHNAME(created_at) as month, COUNT(*) as count')
->groupBy('month')
->pluck('count', 'month')
->toArray();
Create a Blade file named chart.blade.php
in resources/views
and add:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Laravel 12 ChartJS Example</title>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.umd.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h3 class="text-center">Laravel 12 ChartJS Example</h3>
<div class="card mt-4">
<div class="card-body">
<canvas id="myChart" height="100"></canvas>
</div>
</div>
</div>
<script>
// Get the canvas element
const ctx = document.getElementById('myChart').getContext('2d');
// Create the bar chart
new Chart(ctx, {
type: 'bar',
data: {
labels: @json($data['labels']),
datasets: [{
label: 'Monthly Data',
data: @json($data['values']),
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
</body>
</html>
Explanation:
<canvas>
element where the chart will render.@json($data['labels'])
and @json($data['values'])
convert PHP arrays to JavaScript-compatible JSON.Start your Laravel server:
php artisan serve
Visit http://localhost:8000/chart
in your browser. You should see a bar chart displaying the sample data for January to May.
You can customize the chart by modifying the JavaScript in the Blade file. Here are a few examples:
To create a line chart instead of a bar chart, update the type
in the JavaScript:
type: 'line',
To display multiple datasets (e.g., sales and expenses), modify the controller and Blade file.
In ChartController.php
:
$data = [
'labels' => ['January', 'February', 'March', 'April', 'May'],
'sales' => [65, 59, 80, 81, 56],
'expenses' => [28, 48, 40, 19, 86],
];
In chart.blade.php
, update the datasets
:
datasets: [
{
label: 'Sales',
data: @json($data['sales']),
backgroundColor: 'rgba(54, 162, 235, 0.5)',
borderColor: 'rgba(54, 162, 235, 1)',
borderWidth: 1
},
{
label: 'Expenses',
data: @json($data['expenses']),
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderColor: 'rgba(255, 99, 132, 1)',
borderWidth: 1
}
]
To display real data, query your database in the controller. For example, to show user registrations per month:
use App\Models\User;
public function index()
{
$data = User::selectRaw('MONTHNAME(created_at) as month, COUNT(*) as count')
->groupBy('month')
->orderByRaw('MIN(created_at)')
->get()
->pluck('count', 'month')
->toArray();
$labels = array_keys($data);
$values = array_values($data);
$data = [
'labels' => $labels,
'values' => $values,
];
return view('chart', compact('data'));
}
Ensure you have some User
records with created_at
timestamps to see meaningful data.
Integrating ChartJS with Laravel 12 is a fantastic way to add dynamic, interactive charts to your application! This tutorial showed you how to set up a bar chart using sample data, but you can easily adapt it to visualize real data from your database.
With ChartJS’s flexibility, you can create various chart types and customize them to suit your needs. I hope this guide was clear and inspires you to enhance your Laravel projects with data visualization.
Q1: Can I use ChartJS with real database data?
A: Yes! Query your database in the controller using Eloquent (e.g., User::selectRaw(...)
) and pass the results to the Blade view, as shown in Step 7.
Q2: What chart types does ChartJS support?
A: ChartJS supports bar, line, pie, doughnut, radar, polar area, bubble, and scatter charts. Change the type
in the JavaScript to switch chart types.
Q3: Why is my chart not displaying?
A: Check that the ChartJS CDN is loaded, the canvas ID matches the JavaScript, and the data (labels
and values
) is correctly passed. Use browser developer tools to inspect for JavaScript errors.
Q4: Should I use a CDN or npm for ChartJS?
A: The CDN is simpler for quick setups, as shown in this tutorial. Use npm for larger projects to bundle ChartJS with your assets and enable tree-shaking for better performance.
Q5: How do I make the chart responsive?
A: ChartJS charts are responsive by default. Ensure the <canvas>
element is inside a responsive container (e.g., Bootstrap’s container
), and avoid fixed widths/heights unless necessary.
You might also like: