How to access larvel.env variables inside javascript?

I am currently using Algolia for my search engine in the Laravel application, so when I create an entry, it is also sent to the Agolia database. Of course, I want to share my data in an Algolia database with a test suite for local development and a production kit for a live website. I determined which indexes of my Algolia database are used in the JavaScript file.

Now I am wondering how I react accordingly to my variable APP_ENV to change it depending on my current environment? Obviously, I need to put things in an if in my JavaScript, but how do I get my JavaScript to access .env variables correctly?

Hope someone can help me.

Greetings.

+10
javascript php environment-variables laravel
source share
5 answers

You can simply display the env variable as a javascript string in your view:

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

And your .env file will look like this:

NAME = Alex

+21
source share

As you can see from the documentation : now you can easily use env variables by adding the key prefix in your MIX_ file using MIX_ .

MIX_SENTRY_DSN_PUBLIC=http://example.com

After the variable has been defined in your .env file, you can access it through the process.env object.

process.env.MIX_SENTRY_DSN_PUBLIC

+5
source share

There are many ways.

One of the best is to transfer data from the controller to the view:

 if ($app->environment('local')) { // Here you can generate some <script></script> code or you could just generate // hidden div like <div id="environment" style="display:none">local</div> } 

or like this:

 return view('myView')->with('env', $app->environment()); 

Or you can use Session:

 \Session::put('env', $app->environment()) 

Of course, you can create a dedicated route and get it using Ajax, but I don't think this is a good way to do this in a real web application.

+1
source share

A cleaner solution is to use the laracasts/utilities package to send your variables to your file.

Install it using the composer require laracasts/utilities .

Then add use JavaScript; to the top of your controller.

And finally, send your variable as follows: JavaScript::put([ 'foo' => $bar ]); .

+1
source share

When accessing env vars outside the main js file. You can do the following:

 let mix = require('laravel-mix'); require('dotenv').config(); 

then:

 let my_env_var = process.env.MY_ENV_VAR; 

A mix is ​​required and the dotenv config gives you access. :)

0
source share

All Articles