Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

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 a RuntimeException 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.

Learn the fundamentals of PHP 8 (including 8.1, 8.2, and 8.3), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article? Consider leaving a


👋 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.