Cruzito
Cruzito

Reputation: 348

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!!

Upvotes: 2

Views: 256

Answers (1)

MrCode
MrCode

Reputation: 64526

You need to output the variable as raw like so:

<script>
var $items = {!! $json !!};
</script>

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

Upvotes: 3

Related Questions