Requiring .env entries in Laravel

Laravel, Quick Tip

In Laravel you can set your environment specific variables by using the .env file. In the application you can then easily retrieve the variable by using the env('VARIABLE_NAME') function. This file is not be meant to be added to git. This way you can a secret values in your project without accidentally add them to git and sharing them.

Due to the fact that this file is not in git, you may forget to set the variable. This may result in vague errors: An API that is called without credentials may return empty results, and it can take some time to debug this.

Under the hood Laravel uses the Dotenv library. This reads the .env file, parses the contents and makes it available for the application to read. It also has an helper: required. You can feed it an string or an array of strings. It will then validate if it is available. If it is not, it will throw an exception.

Require your variable

There is only one caveat: When Laravel inits the Dotenv library, the instance is not written to the system (view source):

(new Dotenv($app->environmentPath(), $app->environmentFile()))->load();

So we have to create a new instance. For that to do we need to get the path to the .env file. We can retrieve this from the app container:

app()->environmentPath()

To require variables we can place this code in an service provider:

$dotenv = new Dotenv(app()->environmentPath(), app()->environmentFile());
$dotenv->load();
$dotenv->required('MY_CUSTOM_VARIABLE');

Now when you forget to add an environment variable an exception will be thrown and the application quits. If you want a more graceful handling then you can catch the exception (\Dotenv\Exception\ValidationException) and send yourself an e-mail, report it to Slack or choose something else of your liking.

Need a package?

With about anything regarding Laravel, there is a package that can do this for you. It can even validate that the .env variables adhere to your standards. It is called laravel-env-validator and you can find it here.

Want to respond?