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: 1st January 2021
First published: 1st January 2021