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.

1
  • Your file would have to have a .php extension to have any php processed. Commented Apr 19, 2020 at 6:58

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

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.