1

How do i assign a js variable a php value, for example i have this js variable called nr and a php var $nr.

@php
    $gal = \App\Gallery::where('id',$wid[1])->first();
    $p = json_decode($gal->photo,true);
    $nr = count($p);
@endphp

 <script>
    var nr={PHP variable here};</script>
2
  • Not a big fan of using @php ... @endphp in a view file, I'd declare it in the Controller, assign it to the view and use <script>var nr={{$myVar}}</script> in the view file Commented Apr 12, 2020 at 13:39
  • Does this answer your question? laravel-5 passing variable to JavaScript Commented Apr 12, 2020 at 14:01

1 Answer 1

1
  1. Try this var nr= {{!! $nr !!}};
  2. You can change your code a bit and achieve the same result by doing this:
@php
    $gal = \App\Gallery::where('id',$wid[1])->first()->photo;
@endphp

<script>
    var gal = @json($gal)
    var nr = gal.length
</script>
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.