Chartjs-How to install Chart.js in Laravel? ("Uncaught ReferenceError: Chart is not defined")

1👍

Chart.js must be loaded before content in order to use it in any Controller. I was loading my laravel-mix variables after HTML content (because it includes some big libralies like jQuery etc.), so that’s why it couldn’t work.

SOLUTION:

At the end of my document I still have my previous script

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

But now I made a new loadBefore.js file in resources/js directory with one line of code:

require('chart.js/dist/chart.js');

If there will be any reason to put there any other javascript code, it will be easy to put it there.

I also added this file to webpack.mix.js like this:

mix.js('resources/js/loadBefore.js', 'public/js').sourceMaps();

And of course at the end I added this script to the head section in my blade:

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

Now everything is working and I’m using already existing in my Laravel files chart.js file. I don’t know, someone knows an easier solution, so for now I’m accepting my answer, but I’m still open for suggestions.

1👍

why you just dont copy the content of

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script>

in a file at your local, for example: /public/js/chart.js
and load it in head

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

Leave a comment