How to install Chart.js in Laravel? (“Uncaught ReferenceError: Chart is not defined”)

I don’t know, how much time I lost looking for solution for this issue. I wanted to use Chart.js in my Laravel project, so I followed instructions described here.

  1. composer require fx3costa/laravelchartjs (runned)
  2. Fx3costaLaravelChartJsProvidersChartjsServiceProvider::class (added in the right place)
  3. npm i chart.js (used to install chart.js)
  4. In my controller and blade I used code from example 1 (Line Chart / Radar Chart)

After that the error appeared: Uncaught ReferenceError: Chart is not defined. Before and after that I was trying different solutions, but always something was wrong and I think this one should work for me. I probably missed something obvious, but very important.

Have you any ideas? Should I add something to webpack.mix.js or bootstrap.js files after installing with npm?

EDIT:

If I put <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.js"></script> in my head section of blade, everything is working fine, but I’m using laravel-mix to use a locale file instead of link.

Answer

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.