Cruzito Cruzito - 1 year ago 73
JSON Question

Laravel use json from controller in jquery

I am fairly new to laravel and I am trying to replicate something I build in wordpress a while ago with laravel. So my goal is to query some data from the database and use the json_encode of this data in my jQuery.

So in my controller I did this:

public function index()
$kalenderItems = Kalender::orderBy('created_at', 'desc')->get();
$json = json_encode($kalenderItems);

return view('kalender.index', compact('json'));

In my view if I do this:

{{ $json }}

It works obviously, but when I try to do this in my script tags in the same index file, it doesn't work. Unfortunately.

$items = {{ $json }};

I was able to do this in WordPress like this in my script tags

$items = <?php json_encode($data); ?>;

Can I replicate this in laravel or is what I am trying not possible?

Many thanks in advance!!

Answer Source

You need to output the variable as raw like so:

var $items = {!! $json !!};

By using {{ $json }}, the value will be encoded using HTML entites, which breaks the JSON.