javascriptphplaravelenvironment-variables

How to access the laravel .env variables inside javascript?


I am currently using Algolia for my search engine inside a Laravel application, so whenever a record is created it is also sent to the Agolia database. Of course I want to separate my data in the Algolia database with a testset for local development and a production set for the live website. I have defined which indices of my Algolia database are being used in a JavaScript file.

Now I am wondering how do I react accordingly to my APP_ENV variable to change it depending on my current environment? Obviously I need to put stuff into an if statement in my JavaScript but how do I make my javascript access the .env variables properly?

Hopefully somebody can help me out.

Cheers.


Solution

  • You can just echo out the env variable as a javascript string in your view:

    <script>
    
    var name = '{{ env('NAME') }}';
    
    alert(name);
    
    </script>
    

    And your .env file would look like this:

    NAME=Alex