[Chartjs]-How to install Chart.js in Laravel?

11👍

Run this from command line:

npm install chart.js

Add this line in webpack.mix.js:

mix.copy('node_modules/chart.js/dist/chart.js', 'public/chart.js/chart.js');

Then run this from command line:

npm run dev

In the blade you want the chart on:

<script src="{{ asset('chart.js/chart.js') }}"></script>
<canvas id="myChart" width="500" height="200"></canvas>
<script>
  var ctx = document.getElementById('myChart').getContext('2d');
  var myChart = new Chart(ctx, { 
  ...
  }
</script>

3👍

You can register a global Chart variable in app.js like this:

// Chart JS
import Chart from 'chart.js/auto';
window.Chart = Chart;

And then you can use it in the views or in the other JS files with new Chart(....)

1👍

I am having the some problem.

First I can’t bring the library via NPM. I installed it, then I execute "npm run dev". But when I call it in the app it says

1:2573 Uncaught ReferenceError: Chart is not defined
    at 1:2573

If I call it from a CDN, it conflicts with somethig of VUE or Bootstrap. Because it doesn’t work. Except that I erase "defer" word from line from app.blade.php:

    <script src="{{ asset('js/app.js') }}" defer></script>

But again, only calling Charts.Js by CDN. Can’t bring it from NPM.

Hoping somebody has the same problem. Thank you.
Hernán.

1👍

The @Magmatic answer is close.

For newer version like i use v4.x. Revise a bit at:

mix.copy(‘node_modules/chart.js/dist/chart.umd.js‘,
‘public/js/chart.js’);

Add another to hide error notice:

mix.copy(‘node_modules/chart.js/dist/chart.umd.js.map‘,
‘public/js/chart.umd.js.map‘);
mix.copy(‘node_modules/chart.js/dist/helpers.js.map‘,
‘public/js/helpers.segment.js.map‘);

0👍

I would use this library https://github.com/ConsoleTVs/Charts.

Run…

composer require consoletvs/charts

Then publish the config file:

php artisan vendor:publish --tag=charts_config

In config/charts.php, specify your chart type:

'default_library' => 'Chartjs',

Install:

npm i chart.js

From there follow the instructions on creating a chart.

https://charts.erik.cat/create_charts.html#create-a-chart-class

Leave a comment