1

I'm really new into web dev and I'm working on a project which uses the TALL stack:

  • Laravel Mix;
  • Livewire;
  • AlpineJS and;
  • TailwindCSS.

I want to get a PhP variable and store it in a JavaScript variable, so I can do jQuery/JavaScript stuff with it.

The PhP variable is <?php Auth::user()->kyc_status ?> and I would like to store it in a JavaScript variable called kycStatus. The idea could be represented by something like let kycStatus = <?php Auth::user()->kyc_status ?>

Thanks in advance.

2 Answers2

1
<script>
    let kycStatus = {{ Auth::user()->kyc_status }}
</script>
Jacky.S
  • 364
  • 5
  • 17
  • 1
    You probably need to quote it if its a string, `let kycStatus = '{{ Auth::user()->kyc_status }}';` – Qirel Mar 25 '21 at 13:40
  • 1
    I don't think quote is needed, {{ }} represents a variable, you don't put a quote on a variable like `'$variable'`, if the variable is a string type, then kycStatus will get the string type – Jacky.S Mar 25 '21 at 13:52
  • 1
    The quote is for the JS to know its a string, see where I put the quotes in my comment – Qirel Mar 25 '21 at 14:12
  • 1
    If you think the answer is helpful, could you please accept the answer as the right answer, thanks in advance – Jacky.S Mar 25 '21 at 14:14
  • For sure, @Jacky.S. I was about to do that! ;) Could you please explain me the difference on doing {!! json_encode(Auth::user()->kyc_status) !!}; and '{{ Auth::user()->kyc_status }}'; ? – Fernando Rodrigues Coelho Mar 25 '21 at 14:21
  • you could refer to this discussion: https://stackoverflow.com/questions/29308441/using-javascript-to-display-laravels-variable – Jacky.S Mar 25 '21 at 14:23
1

You can do it like following

<script>    
    var kycStatus = {!! json_encode(Auth::user()->kyc_status) !!};
</script>

Or use this Laravel package https://github.com/laracasts/PHP-Vars-To-Js-Transformer to pass some server-side string/array/collection/whatever to your JavaScript.

Junior Gantin
  • 2,102
  • 1
  • 18
  • 24