Laravel Helper Function: env

November 20, 2016 —John Koster

env($key, $default = null)

The env function can be used to get an environment variables value. If an environment value with the given $key exists, its value will be returned. If the given $key does not exist, the $default value will be returned instead, which is null by default. The following examples will show examples of the env function.

The following examples will use the following .env file:

1APP_ENV=local
2APP_DEBUG=true
3APP_KEY=SomeRandomString
4
5DB_HOST=localhost
6DB_DATABASE=homestead
7DB_USERNAME=homestead
8DB_PASSWORD=secret
9
10CACHE_DRIVER=file
11SESSION_DRIVER=file
12
13TEST_TRUE1=true
14TEST_TRUE2=(true)
15
16TEST_FALSE1=false
17TEST_FALSE2=(false)
18
19TEST_NULL1=null
20TEST_NULL2=(null)
21
22TEST_EMPTY1=empty
23TEST_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<?php
2 
3// local
4env('APP_ENV');
5 
6// true
7env('APP_DEBUG');
8 
9// A rather long default value
10env('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.

Some absolutely amazing
people

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.