How to send JSON data from Laravel controller to Blade template for JavaScript use

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.

Wait, you’re passing the variable as grid in your controller but using $coordinates in the blade template. Shouldn’t it be {{ Js::from($grid) }} instead? That mismatch is probably what’s causing the weird parsing issues with your GridSystem library.

You’re double encoding your data. Your controller calls json_encode() and then your Blade template uses Js::from() - that’s encoding twice. This breaks the JavaScript. It looks fine in console.log but crashes when the library tries to use it.

Fix your controller - just pass the raw array:

$coordinates = GridCell::orderBy('position', 'asc')->get()->toArray();
$coordinates["start"] = array("x"=>0, "y"=>0);
return view('dashboard', ["grid" => $coordinates]);

Keep using Js::from() in your Blade template like you’re doing now. It handles all the escaping and encoding for you. I hit this exact same bug with Chart.js data from Eloquent models - wasted hours staring at what looked like identical JSON.