I'm a big fan of validating data, but have you ever wanted to validate your application environment?
For example, what if a specific environment variable is absolutely required for the app to run properly? Or what if you need to ensure that a particular environment variable is an integer or matches a list of specific values? How would you do that?
Laravel uses the excellent Dotenv package for managing environment variables. It contains helper methods to do exactly what I was describing:
// will throw exception: DB_HOST is missing (for any of the env keys)
$dotenv->required(['DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASS']);
// will throw exception: DB_PORT is not an integer
$dotenv->required('DB_PORT')->isInteger();
// will throw exception: DB_CONNECTION is not an allowed value
$dotenv->required('DB_CONNECTION')->allowedValues(['mysql', 'sqlite']);
This API is really nice to work with if you have access to a Dotenv
instance, but we don't have access to that directly in a Laravel app.
Here are two suggestions for at least validating an environment variable is present:
// Option 1: Use the env() helper
$env = env('DB_HOST', fn () => throw new Exception('DB_HOST is missing'));
// Option 2: Use the Illuminate\Support\Env class directly
$env = Env::getOrFail('DB_HOST');
These approaches don't provide the same level of validation as the Dotenv
package, but they're a good start.
Here to help,
Joel
P.S. The code presented as option 1 was shared in our Slack community this week. I love hanging out with smart devs. Always something new to learn.