How to use Chart Js in Laravel

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to use chart js in laravel.

 

How to use chart js in laravel

 

How to use chart js in laravel

Here are the steps to use Chart.js in Laravel:

 

Step 1 - Install Chart.js library via npm using the following command:

npm install chart.js --save

 

Step 2 - Create a new view in Laravel where you want to display the chart.

 

Step 3 - In the view, include the Chart.js library by adding the following code:

<script src="{{ asset('js/Chart.min.js') }}"></script>

Note - Make sure the path to the Chart.js file is correct based on your project's file structure.

 

Step 4 - Create a canvas element in your view where the chart will be displayed:

<canvas id="myChart"></canvas>

 

Step 5 - In your controller, create an array of data that will be used to create the chart. This can be done by querying data from a database or manually creating an array.

 

Step 6 - Create a JavaScript function to initialize the chart. Here's an example of a function that creates a bar chart:

var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
        datasets: [{
            label: 'Sales',
            data: [12, 19, 3, 5, 2, 3, 9],
            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)',
                'rgba(255, 99, 132, 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)',
                'rgba(255, 99, 132, 1)'
            ],
            borderWidth: 1
        }]
    },
    options: {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }]
        }
    }
});

Note: Replace the `labels` and `data` values with your own data.

 

Step 7 - Pass the data array to the view from your controller using the `compact` function:

return view('chart', compact('data'));

 

Step 8 - Finally, call the JavaScript function in your view to initialize the chart:

<script>
    // Call the chart initialization function here
</script>

 

That's it! You should now see your chart displayed in the view. You can customize the chart's appearance and behavior by modifying the chart initialization function. For more information on the available options, refer to the Chart.js documentation.

Comments 0

Leave a comment