Home » Laravel » How to Use ChartJS with Laravel

How to Use ChartJS with Laravel

ChartJS is the most popular JavaScript library for creating charts, plots and diagrams. If you saw beautiful charts on any website, then there is a high possibility that they were built using this library. For example, the AdminLTE admin panel uses ChartJS for graphs.

In this article, we will explain how to install and use ChartJS with Laravel. You may want to use CDNs, the same way as for Bootstrap, but if you want your application to be more reliable, build all assets using npm.

Table of Contents

How to Use ChartJS with Laravel

I assume that you have installed and configured Laravel on your computer. If it is not, check this article.

1. Install JQuery

You may want to use JQuery to find elements for ChartJS. But Laravel does not provide JQuery out of the box. You should install it manually using the command below:

npn install jquery --save

After this, add the following code to the resources/js/bootstrap.js file:

window.$ = require('jquery');

It makes the JQuery variable ($) available in the window object. Now, you can use it in your scripts.

2. Install ChartJS

Now, you can install ChartJS. Run the following command to do this:

npm install chart.js --save

If you want to use ChartJS in your blade files, make it available in the window object. To do this add following code to resources/js/bootstrap.js:

import Chart from 'chart.js'; window.Chart = Chart;

After this ChartJS will be available as a Chart in the app.js and from the window object in the .blade files. Next, rebuild JavaScript assets:

npm run dev

3. Make Graph in blade files

Initializing graphs from blade files is very convenient. You can set graph data directly from the PHP. If Vue.js is disabled, you can paste scripts directly into the content section. In other cases, use instructions from this article. In this article I will use the first method. Create graph.blade.php and add this code to it:

@extends('layouts.app') @section('content') <canvas id="myChart" width="400" height="150"></canvas> <script> document.addEventListener('DOMContentLoaded', function () { const ctx = document.getElementById('myChart'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] } }); }, true); </script> @endsection

Then, register a new route:

Route::get("/graph", function () { return view("graph"); });

Now you can run a built-in web server and open http://localhost:8080/graph in the browser:

You can get the error “Chart is not defined” in the JavaScript console. To fix it ensure that app.js assets are correctly included in the current page and make sure that your script is loaded after the DOMContentLoaded event. The app.js scripts will load after the page is loaded, so if your script executes earlier it will not work.

4. Make Graph in app.js

You may want to place ChartJS initialization code into resources/js/app.js. It allows Laravel Mix to optimize JS code and pack it into a single file. But the data usually should be provided from the blade file. You can provide it using the data-* HTML attribute. The data should be in JSON format. First, change the graph.blade.php file to this look:

@extends('layouts.app') @section('content') <canvas class="chart" width="400" height="150" data-type="line" data-labels="[&quot;Red&quot;, &quot;Blue&quot;, &quot;Yellow&quot;, &quot;Green&quot;, &quot;Purple&quot;, &quot;Orange&quot;]" data-series="[12, 19, 3, 5, 2, 3]" data-color="rgba(255, 0, 0, 1)" data-bg-color="rgba(255, 0, 0, 0.8)" data-border-color="rgba(255, 0, 0, 0.5)" ></canvas> @endsection

All required parameters for ChartJS are configured. I use the “chart” CSS class instead of id because it allows for creating as many graphs as you want. Next, add this JavaScript code to resrouces/js/bootstrap.js or app.js:

let Chart = require("chart.js/dist/chart"); window.Chart = Chart; $(".chart").each(function () { let type = $(this).data("type"); let labels = $(this).data("labels"); let series = $(this).data("series"); let bgColor = $(this).data("bg-color"); let borderColor = $(this).data("border-color"); let color = $(this).data("color"); let options = $(this).data("options"); let ctx = this.getContext("2d"); new Chart(ctx, { type: type, data: { labels: labels, datasets: [ { data: series, color: color, backgroundColor: bgColor, borderColor: borderColor, }, ], }, options: options, }); });

You don’t need to wait until the document is loaded here, because this code will be executed after JQuery and ChartJS initialization. Now, you can rebuild JS assets:

npm run dev

Add a testing route if you haven’t done it earlier:

Route::get('/graph', function(){ return view('graph'); });

Then open this page in the browser:

As you can see, the graph insertion is working.

How to Add ChartJS using CDN

If you don’t want to build assets manually, you can just import ready ChartJS files from CDN. But in this case your application will be dependent on CDN. To do this, just add this line to the <head> section in your layout file. For example resources/views/layouts/app.blade.php:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

Now, you can use it in your scripts.

Wrapping Up

In this article we have explained how to install and use ChartJS in Laravel 9 using npm or CDN. As you can see it is very simple. What library do you use for displaying charts? Tell us using the comment form below.

Leave a Comment