Get All ENV variables in Laravel
Asked Answered
H

3

10

Laravel has a .env file that contains various variables. Is there a way to get all the variables in one line of PHP code? I don't want to write

echo env('APP_DEBUG')
echo env('APP_URL')
etc...

I have tried

env("*")
env("*")

but none works.

Hjerpe answered 31/7, 2019 at 8:54 Comment(5)
Do you want all values from the .env file or all environment variables? And why would you want this?Cheesy
I don't think there's an in-built mechanism for this. You may write your own code to read the file though.Ballew
@Cheesy because we have a lot of stuff in there aside from the default Laravel ENV variables. we will restrict displaying the password or secret variables.Hjerpe
@Ballew that was my first hunch but .env file is outside the public folder in laravel.Hjerpe
You can read any file on your server with PHP that the web server user has access to.Cheesy
P
26

This should work:

$_ENV; // gives all env variables.


To get a single env variable:

$_ENV['VARIABLE'];
Polynesia answered 31/7, 2019 at 9:0 Comment(3)
Wait this isn't for .env variables for Laravel, this is for PHP isn't it? OP was asking about retrieving variables from the .env file.Rinaldo
Nope @amir, laravel will load the . env file so you can access its variables on $_ENV you can try that on your local to see if thats working ( it is working btw )Serapis
Does depend on the PHP ini setup what var is loading the Laravel .envs https://mcmap.net/q/82607/-why-is-my-_env-emptyDecade
M
10

The only safe way for reading all env() attributes is to use Dotenv directly :

$env = Dotenv\Dotenv::createArrayBacked(base_path())->load()

This method is usable on every environment : cli, dispatched jobs, without proper web server and even if php.ini is ignoring env.

Menorah answered 20/5, 2021 at 10:7 Comment(2)
For older versions (in 5.8 at least): $env = \Dotenv\Dotenv::create(base_path())->load();Perfumery
Note that because this method circumvents Laravel's own implementation, there is no guarantee that the 'FOO' key in this output will match env('FOO'). For example, if the configuration is cached via php artisan config:cache, calls to the env() helper may return values that differ from those output via this command. Just a heads-up.Undry
D
0

You can do the following:-

php artisan tinker

$_ENV
Drupelet answered 20/7, 2023 at 11:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.