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>
Andrii Omelchenko
  • 13,183
  • 12
  • 43
  • 79
Cristian Cutitei
  • 120
  • 3
  • 12
  • 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 `` in the view file – brombeer Apr 12 '20 at 13:39
  • Does this answer your question? [laravel-5 passing variable to JavaScript](https://stackoverflow.com/questions/30074107/laravel-5-passing-variable-to-javascript) –  Apr 12 '20 at 14:01

1 Answers1

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>
Commander
  • 264
  • 2
  • 12