7

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.

James Arnold
  • 698
  • 3
  • 9
  • 22
  • Do you want all values from the `.env` file or all environment variables? And why would you want this? – Jerodev Jul 31 '19 at 08:58
  • I don't think there's an in-built mechanism for this. You may write your own code to read the file though. – linuxartisan Jul 31 '19 at 08:58
  • @Jerodev 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. – James Arnold Jul 31 '19 at 13:45
  • @linuxartisan that was my first hunch but .env file is outside the public folder in laravel. – James Arnold Jul 31 '19 at 13:46
  • You can read any file on your server with PHP that the web server user has access to. – Jerodev Jul 31 '19 at 14:36

3 Answers3

22

This should work:

$_ENV; // gives all env variables.


To get a single env variable:

$_ENV['VARIABLE'];
Zeshan
  • 2,496
  • 3
  • 21
  • 26
  • 4
    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. – Amir Asyraf Jul 21 '20 at 03:42
  • 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 ) – Ugur Kazdal Dec 16 '20 at 07:34
  • Does depend on the PHP ini setup what var is loading the Laravel .envs https://stackoverflow.com/questions/3780866/why-is-my-env-empty – rhand Jan 03 '21 at 05:54
5

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.

Ifnot
  • 4,914
  • 4
  • 33
  • 47
  • For older versions (in 5.8 at least): `$env = \Dotenv\Dotenv::create(base_path())->load();` – cam8001 Aug 21 '21 at 11:53
  • 1
    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. – Ben Johnson Mar 03 '22 at 17:14
0

You can do the following:-

php artisan tinker

$_ENV
boeing
  • 302
  • 7
  • 19