April 14, 2018 —John Koster
The env
helper function is used to retrieve the value of an environment variable. You may supply a $default
value to be returned if there is no value currently set for the provided $key
.
The signature of the env
function is:
1function env(2 $key,3 $default = null4);
The following examples will use the following .env
environment file:
1APP_ENV=local 2APP_DEBUG=true 3APP_KEY=SomeRandomString 4 5DB_HOST=localhost 6DB_DATABASE=homestead 7DB_USERNAME=homestead 8DB_PASSWORD=secret 910CACHE_DRIVER=file11SESSION_DRIVER=file1213TEST_TRUE1=true14TEST_TRUE2=(true)1516TEST_FALSE1=false17TEST_FALSE2=(false)1819TEST_NULL1=null20TEST_NULL2=(null)2122TEST_EMPTY1=empty23TEST_EMPTY2=(empty)
The returned value will appear above the function call as a comment (the actual values returned will likely be different based on application specifics and environment configuration):
1// local2$valueOne = env('APP_ENV');3 4// true5$valueTwo = env('APP_DEBUG');6 7// A rather long default value8$valueThree = env('NonExistent', 'A rather long default value');
The env
function will automatically convert boolean string representations and null representations into their corresponding PHP value. In the above example configuration file, the values returned for TEST_TRUE1
, TEST_TRUE2
, TEST_FALSE1
and TEST_FALSE2
will automatically be converted to a boolean type. The values returned for TEST_NULL1
and TEST_NULL2
will automatically be converted to a null
type. The values returned for TEST_EMPTY1
and TEST_EMPTY2
will actually be an empty string, with a length of 0
.
∎
The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.