They should be available in the way you wrote, but in the compiled js you need to tell it where to look. So try this to access a labels variable.
let labels = window.labels
And set them in the same way in blade
window.labels = @json($labels)
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Trying to get my head around Vite in Laravel, so I can move to a modern bundler. I'm starting with just vanilla JS.
The concept I'm stuck on is passing data from a controller to Javascript. Traditionally I would pass the data from controller to blade view and then place the JS code in a tag in the footer of each individual blade page. However, this seems to go against the pattern of putting JS in the resources/js folder and bundling them using Vite.
For example Chart.js needs a data array to build a chart:
const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [{ label: '# of Votes', data: [12, 19, 3, 5, 2, 3], }] }, options: { ... } });
Previously I would have build the data array in my controller, passed it the blade view and then output it in a tag in the footer. If I'm now putting all my JS in app.js, how do I access this data array?
I've had a go at specifying variables in the blade file but the content in the script tag doesn't seem to be able to access the code in the app.js. I'm pretty sure I'm just not understanding a concept here!
Please or to participate in this conversation.