Laravel: do not use env() elsewhere than in config files

Posted on March 12, 2018

In Laravel, the .env is a poweful file where you can put all your dynamic and personal values such as database credentials or API keys. You can add every key you want in this file.

Let' say we want to use an external API to retrieve kittens in our app, and we need to use a secret key to call this API. We can add the key to our .env:

KITTENS_SECRET_KEY=a1b2c3d4e5

Next, wherever we want to fetch the API, we can retrieve this key:

// app/Services/Kittens.php

$key = env('KITTENS_SECRET_KEY');

// Fetch the API with curl or Guzzle or whatever you want

Now we have a beautiful app displaying kittens, what if we want to deploy in production ?

If you have read the deployment section of the documentation, you know you can optimize your app, running some artisan commands.

One of them is php artisan config:cache, which will cache all config values.

This will broke our app. Why ? Because, even if it's not obvious at first, once the configuration has been cached, the .env file will not be loaded and all calls to the env function will return null .

In our above example:

// app/Services/Kittens.php

$key = env('KITTEN_API_SECRET_KEY'); // This will be null

To fix this, we have to put all our env calls in config files.

// config/kittens.php

return [

    'secret_key' => env('KITTENS_SECRET_KEY')
		
];

Then call config instead of env:

// app/Services/Kittens.php

$key = config('kittens.secret_key');

// Fetch the API with curl or Guzzle or whatever you want

Now, we can cache our config without breaking our app ๐ŸŽ‰