I’m working on a Laravel project where I need to pass JSON data to JavaScript in my Blade template. I’m having issues with the data encoding when using Laravel’s built-in JSON helper.
<script>
const mapData = {{ Js::from($coordinates) }};
console.log(mapData);
var mapInstance = new GridSystem.create(document.getElementById('grid-container'),
{
'display': {'visible':true},
'text': {
'visible': true,
'truncate': true,
'formatter': function(content, properties) {
return properties.cell.x + ", " + properties.cell.y;
}
},
'configuration':{
"type":"square-grid",
"cells": mapData,
}
}
);
</script>
The weird thing is that when I manually copy the output from console.log and hardcode it instead of using the Blade helper, everything works fine. But with the helper I get JavaScript errors about invalid transform and viewBox values.
Here’s my controller code:
$coordinates = GridCell::orderBy('position', 'asc')->get()->toArray();
$coordinates["start"] = array("x"=>0, "y"=>0);
return view('dashboard', ["grid" => json_encode($coordinates)]);
Why isn’t the JSON encoding working properly through Blade? The data looks correct when logged but the JavaScript library can’t parse it.