How to Get .env Variables in Laravel?

Last updated on December 29, 2022 by Ayaz Ali Shah

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.


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" => ""
  "LOG_CHANNEL" => "stack"
  "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

// Output: Laravel

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

// Output:

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

// Output: mysql


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.

Related Posts

Tags: Laravel,