laravel / lumen access .env values in middleware

Aaron picture Aaron · Apr 12, 2016 · Viewed 7.8k times · Source

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?

Answer

Alexey Mezenin picture Alexey Mezenin · Apr 12, 2016

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'