2

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

1
  • $items = "{{ $json }}"; Commented Jun 3, 2016 at 10:22

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much friend!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.