1

I'm building a site with Laravel 8 and trying to pass PHP variables into JavaScript. At first I was using this kind of construction in my Blade file:

<script>
  let x = {{ $x }};
</script>

but this gets mangled by the format-on-save action in VSCode because the braces get interpreted as JavaScript and separated by spaces.

As an alternative, I've tried to install Laracasts/Utilities, following the instructions here. After carrying out all the steps, however, the controller doesn't recognize JavaScript:

<?php

namespace App\Http\Controllers;
...
use JavaScript;               // <--- no info on mouseover

class XController extends Controller
{
  public function f()
  {
    JavaScript::put([...]);   // <--- Undefined type 'JavaScript'

I'm a beginner at PHP and Laravel, so this is beyond me. It seems that the alias isn't working properly (even though I listed it in aliases in config/app.php) based on the fact that no information pops up when I mouse over use JavaScript in VSCode. I've tried running magic commands like php artisan optimize:clear, php artisan config:clear, and composer dump-autoload, but they didn't change anything and maybe aren't relevant. What else can I try at this point?

1 Answer 1

1

there is easy way to pass php variable to tag, however I'm also not much experienced and I feel like it is kind of a workaround. So there are 2 simple steps:

  1. In your blade add:

    <input id="x" type="hidden" value="{{ $x }}>

  2. In the script get element value:

    var x = document.getElementById("x").value

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

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.