11

Is there any way to access .env vals from inside of a middleware script?

I have tried to do so by env('KEY') but this seems to return null most of the time.

Does any one know of a better way to do this inside of middleware or a way to insure the .env file has been loaded before the middleware runs?

Aaron
  • 167
  • 1
  • 1
  • 10

1 Answers1

17

You can use config() to access .env variables. For example, if you want to get MySQL port, use this:

$mysqlPort = config()['database']['connections']['mysql']['port'];

To get all available variables, you can do dd(config());

If you want to use custom variables in .env, you also can do this:

CUSTOM=hello

And to get this variable, use env() helper:

echo env('CUSTOM'); // Will output 'hello'
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
  • Thanks Alexey but this actually does not work. Whats returned does not contain any of my custom variables. – Aaron Apr 12 '16 at 18:55
  • Do you want to put custom var in `.env` and then get it in your app code? Please look at updated answer. – Alexey Mezenin Apr 12 '16 at 19:06
  • Yes and this works but not inside of middleware. About 90% of the time it will be null form inside of middleware. – Aaron Apr 12 '16 at 19:08
  • is there something similar to app()->environment() to pull other .env values? – Aaron Apr 12 '16 at 19:17
  • 1
    Does `getenv('CUSTOM')` work in middleware? Also, maybe creating custom config file in `config` direcotry and using it is an option? – Alexey Mezenin Apr 12 '16 at 19:37
  • Thanks for the help, I think the issue i was having was from also trying to get the APP_KEY. It looks like all is working with both getenv() and just env() as long as I get retrieve just custom vars. Not sure why it did not work when i first removed the env(APP_KEY) but its working now. Maybe lumen had something cached. – Aaron Apr 12 '16 at 21:10