0

I want to add environment variable key in my bootstrap.js file (in laravel), but the php tags are recognised as strings.

My resources/js/bootstrap.js file

$(document).on('change', '#country', function(event){
    var key = '<?php echo config("app.key"); ?>';
    console.log('key: '+ key);
});

 //out put in console 
// key: '<?php config("app.name"); ?>';

Please guide me on this.

Greatest
  • 1
  • 3

2 Answers2

2

No you can't using PHP in JS file. You can put JS in your blade layout :

layout.blade.php

    <body>
    ....

    <script>
    $(document).on('change', '#country', function(event){
        var key = '{{ config("app.key") }}';
        console.log('key: '+ key);
    });
    </script>
</body>
<html>

Alternative, you can use @stack in your view. Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout :

layout.blade.php

<html>
    <head>
        <!-- push target to head -->
        @stack('scripts')
    </head>
    <body>

        <!-- or push target to footer -->
        @stack('scripts')
    </body>
</html

view.blade.php

@push('scripts')
<script>
$(document).on('change', '#country', function(event){
    var key = '{{ config("app.key") }}';
    console.log('key: '+ key);
});
</script>
@endpush

Check my answer

Wahyu Kristianto
  • 8,719
  • 6
  • 43
  • 68
0

I would suggest to put the appkey into the head section of your html code. This is usually done in your main layout blade file

<html>
 <head>
  .....
   <script>
     window.AppKey = '{{ config("app.key") }}';
   </script>
 </head>
 <body>
 .....

You may then access the key from anywhere in your JS code, from a js file or embedded code

$(document).on('change', '#country', function(event){
    console.log('key: '+ window.AppKey);
});

It should be also possible to just use AppKey to access the value.

Edwin Krause
  • 1,766
  • 1
  • 16
  • 33