Using JavaScript to display Laravel’s Variable [duplicate]

For more complex variable types like arrays your best bet is to convert it into JSON, echo that in your template and decode it in JavaScript. Like this:

var jobs = JSON.parse("{{ json_encode($jobs) }}");

Note that PHP has to run over this code to make it work. In this case you’d have to put it inside your Blade template. If you have your JavaScript code in one or more separate files (which is good!) you can just add an inline script tag to your template where you pass your variables. (Just make sure that it runs before the rest of your JavaScript code. Usually document.ready is the answer to that)

    var jobs = JSON.parse("{{ json_encode($jobs) }}");

If you don’t like the idea of doing it like this I suggest you fetch the data in a separate ajax request.

Leave a Comment