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.

1
  • Put your PHP data in a html data attribute and get it with javascript. Commented Mar 25, 2021 at 13:21

2 Answers 2

1
<script>
    let kycStatus = {{ Auth::user()->kyc_status }}
</script>
Sign up to request clarification or add additional context in comments.

6 Comments

You probably need to quote it if its a string, let kycStatus = '{{ Auth::user()->kyc_status }}';
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
The quote is for the JS to know its a string, see where I put the quotes in my comment
If you think the answer is helpful, could you please accept the answer as the right answer, thanks in advance
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 }}'; ?
|
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.

3 Comments

There's also a @json blade directive, laravel.com/docs/8.x/blade#rendering-json
Yes :thumbs_up _
This solution also worked. Thanks @JuniorGantin. What is the difference on doing {!! json_encode(Auth::user()->kyc_status) !!}; and '{{ Auth::user()->kyc_status }}'; ?

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.