Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Laravel - Throw Exception If Environment Variable Not Set

Implement a defensive step in your Laravel framework by throwing an exception if an expected environment variable is not set, rather than reverting back to some default that is probably not appropriate.

Steps

return [
    'system_url' => env('SYSTEM_URL', function () { throw new Exception('SYSTEM_URL is empty'); }),
    'embed_url' => env('EMBED_URL', function () { throw new Exception('EMBED_URL is empty'); }),
];
    /*
    |--------------------------------------------------------------------------
    | Application Environment
    |--------------------------------------------------------------------------
    |
    | This value determines the "environment" your application is currently
    | running in. This may determine how you prefer to configure various
    | services the application utilizes. Set this in your ".env" file.
    |
    */

    'env' => env('APP_ENV', function () { throw new \App\Exceptions\ExceptionMissingEnvironmentVariable('APP_ENV'); }),

References

Last updated: 26th August 2022
First published: 1st January 2021

This blog is created by Stuart Page

I'm a freelance web developer and technology consultant based in Surrey, UK, with over 10 years experience in web development, DevOps, Linux Administration, and IT solutions.

Need support with your infrastructure or web services?

Get in touch