Fail-safe way of accessing environment variables in Laravel
Environment variables are tricky little things that we use in our Laravel applications to store sensitive information such as API keys, database credentials, and so on. And there are two ways to access them in your Laravel application.
- Using the global
env()
helper function - Using the
Illuminate\Support\Env::get()
method
I said “tricky” because the problem with both of these methods is that they don’t provide a fail-safe way of accessing environment variables. Meaning that they silently fail if the environment variable is not found in the .env
file. And that can cause serious issues if not tracked early on.
To fix this, Laravel 10.x now comes with a new
Illuminate\Support\Env::getOrFail()
method which will throw aRuntimeException
exception if the environment variable is not found in the.env
file. I got to know about it thanks to Ash!
So, if you want to access an environment variable called SOME_PUBLIC_KEY
in your application, you can do so like so.
use Illuminate\Support\Env;
Route::get('/', function () {
$someApi = Env::getOrFail('SOME_PUBLIC_KEY');
});
This will throw a RuntimeException
exception if the SOME_PUBLIC_KEY
environment variable is not found in the .env
file.
RuntimeException: Environment variable [SOME_PUBLIC_KEY] has no value.
I think this helps ensure that you don’t have any missing environment variables in your application so that you don’t pull your hair out finding weird bugs in your application.
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.