How to Get .env Variables in Laravel?

Laravel takes environmental variables from the .env file located in the root directory. To get all environment variables from the .env file in Laravel we can use the PHP super global variable $_ENV. It returns all environmental variables in array format.

Let’s retrieve them in the controller, so add the below code to the method where you want to get them.

dd($_ENV);

We passed the super global variable $_ENV into the dd() function for die and dump. It returns the following array

array:42 [▼
  "APP_NAME" => "Laravel"
  "APP_KEY" => "base64:F8bsR..."
  "APP_DEBUG" => "true"
  "APP_URL" => "http://127.0.0.1:8000/"
  "LOG_CHANNEL" => "stack"
  "LOG_DEPRECATIONS_CHANNEL" => "null"
  "LOG_LEVEL" => "debug"
  "DB_CONNECTION" => "mysql"
  "DB_HOST" => "localhost"
  "DB_PORT" => "3306"
  "DB_DATABASE" => "laravel9"
  "DB_USERNAME" => "root"
  "DB_PASSWORD" => ""
  …
]

We can get a single value from the above array by adding an index or key into the super global variable $_ENV. Following is an example

$_ENV[‘APP_NAME’]
// Output: Laravel

We have one more PHP function getenv() that retrieves an environment value. Below is an example

getenv('APP_URL')
// Output: http://127.0.0.1:8000/

Laravel also provides a function env() that retrieves a value from the environment. Below is an example

env('DB_CONNECTION');
// Output: mysql

Conclusion

To retrieve all environmental variables we can use PHP super global variable $_ENV and to getenv() the function that accepts the variable’s key and returns its value.