Chart.js is a flexible JavaScript charting library for designers & developers. It currently provides 8 chart types. In this tutorial, we will demonstrate how to install and use Chart.js via NPM in a Laravel application.
composer create-project laravel/laravel chartjs-laravel-9
cd chartjs-laravel-9
php artisan serve
You should see the default Laravel welcome page by accessing http://127.0.0.1:8000/
from your browser:
In this step, we need to set up the Javascript for Chart.js.
npm install
npm install chart.js
resources/js/mychart.js
:import Chart from 'chart.js/auto';
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
new Chart(
document.getElementById('myChart'),
config
);
In this file, we imported Chart.js library via import Chart from 'chart.js/auto';
, and created a simple line chart identified by DOM id myChart
.
It is important to import the Chart.js library first, otherwise, you will encounter an error message as shown below when loading the view page later on:
Uncaught ReferenceError: Chart Is Not Defined
resources/js/app.js
and import our chart Javascript file:import './mychart.js';
npm run dev
You should see a Laravel Mix message indicating successful compilation.
resources/views/chartjs.blade.php
:<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Chart.js with Laravel 9</title>
</head>
<body>
<div style="width: 600px; margin: auto;">
<canvas id="myChart"></canvas>
</div>
<script src="{{ mix('/js/app.js') }}"></script>
</body>
</html>
In the view, we did two main tasks:
We created a DOM element DIV
with the id of myChart
.
We load the Javascript file via Laravel's Mix plugin.
Create a route rule to allow us to browse the view file at routes/web.php
:
Route::get('/chartjs', function () {
return view('chartjs');
});
Now navigate to URL http://127.0.0.1:8000/chartjs
from your browser and you should see a nicely working line chart as shown below: