How to fetch specific key from .env file in Laravel 8 in best way?

The .env files stores many environment variables that we use in the Laravel application. We can fetch specific key from .env file using the functions explained below.

Fetch specific key from .env file

A .env file may have any type of application data. This data is used throughout the application. For example, consider the database configurations as shown below.

DB_PORT=3306
DB_HOST=mysql
DB_USERNAME=scratch
DB_CONNECTION=mysql
DB_PASSWORD=password
DB_DATABASE=example_app​

If you want to use any one of the keys above in your controller or any other classes or file. You can use the function below to fetch the value.

# print the value of DB_HOST
echo env('DB_DATABASE', false);

The second value passed to the env function (false) is the “default value”. It will return if no environment variable exists for the given key.

All of the variables listed in the .env file can be loaded into the $_ENV PHP super-global when an application receives a request. However, you can also use the env function as above to retrieve values from these variables in your configuration files. In fact, on reviewing Laravel configuration files, you will notice many of the options are already using this function. For example, as shown below.

'debug' => env('APP_DEBUG', false),

Similarly, as above the second value (false) is passed to the env function is the “default value”. or the ‘APP_DEBUG’ variable.

.env to determine the current environment

The current application environment can be determined using the APP_ENV variable from your .env file. You can access this value via the environment method on the App façade. 

use Illuminate\Support\Facades\App;
$environment = App::environment()

You can also pass arguments to the environment method to determine if the environment matches a given value. This method will return true if the environment matches any of the given values.

if (App::environment('local')) {
    // The environment is local
}
if (App::environment(['local', 'staging'])) {
    // The environment is either local OR staging...
}

Leave a Comment