TailTemplate Build stunning websites faster with our pre-designed Tailwind CSS templates

How to Use Chartjs in Laravel

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.

Laravel Setup

  • Install a brand-new Laravel project via composer
composer create-project laravel/laravel chartjs-laravel-9
  • Start the Laravel dev server by running the command below.
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:

Chart.js Setup

In this step, we need to set up the Javascript for Chart.js.

  • Install Laravel packages required by Laravel
npm install
  • Install Chart.js Javascript
npm install chart.js
  • Create a Javascript for our own chart 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 
  • Edit resources/js/app.js and import our chart Javascript file:
import './mychart.js';
  • Now run the command below to compile Javascript:
npm run dev

You should see a Laravel Mix message indicating successful compilation.

Render the Chart.js View

  • Create a very simple view 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');
});

Result

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: