How to access the laravel .env variables inside javascript?
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
As the documentation suggests: you can use an env
variable by prefixing it in your .env
file with MIX_
.
e.g: MIX_SENTRY_DSN_PUBLIC=http://example.com
After the variable has been defined in your .env
file, you can access it from a javascript file with the process.env
object.
e.g: process.env.MIX_SENTRY_DSN_PUBLIC
If accessing the env vars from outside of 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;
Requiring mix and the dotenv config gives you access. :)