Transferring JSON data to frontend in Laravel using Blade templates

I’m having trouble with JSON rendering in Laravel 12 and Blade. The docs say to use {{ Js::from($map) }}, but it’s not working right. The data is there, but Blade isn’t handling it correctly.

Here’s my JavaScript:

const hexes = {{ Js::from($map) }};
console.log(hexes);
var hex = new OI.hexmap(document.getElementById('hexmap'), {
  grid: { show: true },
  label: {
    show: true,
    clip: true,
    format: (txt, attr) => `${attr.hex.q}, ${attr.hex.r}`
  },
  hexjson: {
    layout: 'odd-r',
    hexes: hexes,
  }
});

I’m trying to create a hexagon map using a library. But I’m getting errors like Unexpected value translate(NaN NaN) and Unexpected value NaN NaN NaN NaN. It works fine if I hardcode the JSON though.

My PHP code looks like this:

$hexagons = HexTile::all()->toArray();
$hexagons['center'] = ['x' => 0, 'y' => 0];
return view('map', ['hexData' => json_encode($hexagons)]);

Any ideas on what I’m doing wrong here?

hey max, i had a similar problem. try using {!! !!} instead of {{ }} for raw output. like this:

const hexes = {!! $map !!};

also double-check ur $map variable. make sure it’s formatted correctly for the hexmap library. good luck!

It seems you’re encountering a common issue with JSON serialization in Laravel. Have you considered using the @json Blade directive? It’s designed specifically for this purpose and might resolve your problem. Try modifying your JavaScript like this:

const hexes = @json($map);

This approach automatically applies proper JSON encoding and escaping. Also, ensure your $map variable in the controller is properly structured for the hexmap library. You might want to double-check the format of your HexTile model’s data. If the issue persists, try debugging by logging the raw $map data before passing it to the view to verify its structure.

hmm interesting issue! have u tried using json_encode() directly in your blade rather than Js::from()? try:

const hexes = {!! json_encode($map) !!};

also check if $map’s structure suits the hexmap library. what does $map contain?