1

I am passing an array from my controller.

Now, I put this code inside my Laravel 6.* Blade View,

<script>
    var app = <?php echo json_encode($array); ?>;
</script>

This works just fine.

However, if I put the same piece of line (or any of the following lines) inside my custom app.js file, this doesn't work.

var app = <?php echo json_encode($array); ?>;

var app = {!! json_encode($array->toArray()) !!};

var app = '<?php echo json_encode($array); ?>';

Each time I am getting an invalid syntax error.

I am not sure if this is a valid ques for StackOverflow, but I have already tried all other similar solutions and none of them is working for me.

2 Answers 2

1

That's because you have no access to write php code in js file or you can use Ajax to get php variable.

In your statement if you put your code in your blade file before including app.js file you will be able to get app variable in your js file. Ex:

<script>
var app = @json($array)
</script>
<script src="path to your app js file"></script>

And now in your app js file if you print app variable you will see the result console.log(app); in your app.js file

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

Comments

0

One thing you can do is to move javascript to template and create route to it as:

Route::get('/app.js', function () {
    $result = view('app', ['array' => [1,2,3,5,8]]);
    return Response::make($result, 200)
        ->header('Content-Type', 'application/javascript');
});

Then in resouces\views

<script>
    var app = <?php echo json_encode($array); ?>;
</script>

Common way of doing this is to create end point that returns json only and then use e.g. fetch api or axios library on client side.

Something like this:

Route::get('/app', function () {
    return [1,2,3,5,8];
});

<script>
    fetch(endPointUrl("/app")).then(response => {
        console.log(response);
    }).catch(error => {
        console.error(error);
    })
</script>

Where endPointUrl is just a helper function that creates full url.

Comments

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.