How to send JSON data from Laravel to Blade for frontend use?

I’m having trouble with JSON rendering in Laravel 12 and Blade. The docs show how to do it, but it’s not working for me. Here’s what I’m trying:

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
  }
});

It’s for a HexJSON thing using a Hexmap Library. The library throws errors about NaN values. But if I hardcode the JSON, it works fine.

My PHP looks like this:

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

Any ideas why the JSON isn’t getting to the frontend correctly? I’m stumped!

hey iris, have u tried debugging the json output? maybe try console.logging the raw json before parsing it. Also, are u sure the php array structure matches what the hexmap library expects? sometimes theres subtle differences that can trip things up. lemme know if u need more help troubleshooting!

hey iris72, have u tried using the @json blade directive instead? like this:

const hexes = @json($map);

it’s a bit cleaner and might solve ur issue. also, double-check that $map is actually set in ur controller before passing it to the view. hope this helps!

I encountered a similar issue when working with JSON data in Laravel and Blade. One solution that worked for me was using the json_encode() function with the JSON_NUMERIC_CHECK flag. This ensures that numeric strings are converted to numbers, which might be causing the NaN errors you’re seeing.

Try modifying your controller code like this:

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

Then in your Blade template, you can use it like this:

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

This approach should preserve the correct data types and potentially resolve the issues you’re facing with the Hexmap Library.