[Chartjs]-Passing data from a controller to ChartJS – Laravel

1👍

You can’t insert a variable from Laravel into an asset file. You can only insert in views. Assets are supposed to be the part that doesn’t change across requests.

The usual way is to insert the data in the view and store it in a global JS variable that the script can access.

I.e. in home.blade.php do this:

<script>
var datasets = [@json($countVisits), @json($recentVisits)]

// or using an object
var theDatasets = {
    countVisits: @json($countVisits),
    recentVisits: @json($recentVisits)
}

//or directly
var countVisits = @json($countVisits)
var recentVisits = @json($recentVisits)
</script>

<!-- include your dashboard.js afterwards -->

And then you can use the variable inside the dashboard.js in a way that corresponds to how you stored it:

//from array
datasets[0]

//from object
theDatasets.countVisits

//directly
countVisits

The other ways to solve this would be

  • load data via AJAX. But this shifts the problem that you have to give or hardcode the route
  • put all that chart javascript in the view (I would do this if it’s only used in one view, you can also include it from a subview if you want the code organized)
  • create the javascript file as a dynamic view and let blade insert the data into it. I have never seen this done and it doesn’t seem appropriate, but it’s probably possible.

Leave a comment