How to send JSON data from Laravel backend to Blade template frontend

I’m working with Laravel and trying to send JSON data to my Blade template. I followed the official docs but I’m having trouble with the Js::from() helper method.

<script>
const coordinates = {{ Js::from($gridData) }};
console.log(coordinates);
var mapInstance = new GridLib.create(document.getElementById('mapContainer'),
{
    'display': {'visible':true},
    'text': {
        'visible': true, 
        'truncate': true, 
        'formatter': function(text,attributes) {
            return attributes.cell.x + ", " + attributes.cell.y;
        }
    },
    'gridconfig':{
        "type":"offset-r",
        "cells": coordinates,
    }
}
);
</script>

When I use the Blade helper, my grid library shows errors like Unexpected value translate(NaN NaN) and Unexpected value NaN parsing viewBox. But if I manually copy the console output and paste it directly into the code, everything works fine.

My controller code looks like this:

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

The data seems correct when logged, but something about how Blade processes it breaks the grid rendering. Any ideas what might be wrong?

You’re double-encoding your JSON data. Your controller calls json_encode() and then Blade uses Js::from(), which encodes it again. This breaks the JavaScript and messes up your grid library’s parsing. Just remove json_encode() from your controller and pass the raw array: $cells = GridCell::orderBy('position', 'asc')->get()->toArray(); $cells["start"] = array("x"=>0, "y"=>0); return view('dashboard', ["gridData" => $cells]);. The Js::from() helper already handles JSON encoding and escapes everything properly for JavaScript. When you manually copied the console output, you bypassed this double-encoding mess - that’s why it worked. This’ll fix the NaN errors in your grid.

Classic Laravel gotcha! Drop @dump($gridData) in your blade template before the Js::from() call to check the structure. Eloquent relationships or model attributes can mess up serialization - breaks JS parsing without throwing console errors. Also check if your GridCell model has hidden/appended attributes causing issues.

Hmm, interesting - what data type are your x and y coordinates? Eloquent sometimes returns strings instead of integers, which causes NaN errors. Are you casting them as numbers in your GridCell model, or should the JavaScript parse them differently?