Environment Variables in Laravel

By: Sujendra      Posted On: 04 Nov, 2017      Category: Laravel

PHP provides super global variables and we use $_SESSION and $_COOKIES most of the time in our application. $_ENV is also a super global variable in PHP. In Laravel 5 $_ENV variable used to another way to store application related credentials like database credentials, API credentials, SMTP credentials etc.

Why we use Environment Variables ?

When we develop any web application, we need to set of different credentials for local, development and production server.  When a project get is completed, we upload it to production server and also update credentials for production environment. This is just like config.php file in core php project where credentials are configured and we change in it and then upload same file to production server.

It is often helpful to have different configuration values based on the environment where the application is running. For example, on local server you wish to use file for session storage and redis on production server.

 

PHP dotenv

Laravel 5.0 is using PHP dotenv(https://github.com/vlucas/phpdotenv), a PHP library that loads  environment variables from .env to getenv() and $_ENV

 

Env in Laravel

Laravel 5 source code will have .env.example. You can rename it to .env and add variable what ever you want to add. If you have already .env file in laravel source code, you can edit this file and add variable as per your need. For eg.

APP_ENV=local

APP_KEY=SomeRandomString

DB_USERNAME=homestead

DB_PASSWORD=homestead

If you print $_ENV , it will show you all variable added in .env file.

echo '<pre>'; print_r($_ENV); die;

array:4 [

  "APP_ENV" => "local"

  "APP_KEY" => "SomeRandomString"

  "DB_USERNAME" => "homestead"

  "DB_PASSWORD" => "homestead"

]

You can use $_ENV['DB_USERNAME'] to access  DB_USERNAME value.

echo $_ENV['DB_USERNAME'];

// SomeRandomString

In Laravel, we use env($arg1, $arg2) helper function to set and retrieve value of any env variable. Ex:

env('DB_USERNAME', 'someuser');

Here DB_USERNAME is variable set in .env file.  The second value(someuser) passed to the env function is the "default value". This value is used if no environment variable exists for the given key, someuser will be used as default value. If  DB_USERNAME is not defined in .env file, default value(someuser) will be set automatically.

 

How to use evn variable in Laravel soruce code.

In database.php file we can use env function like below

'mysql' => [          

            'host'      => env('DB_HOST', '127.0.0.1'),

            'database'  => env('DB_DATABASE', 'SomeDatabaseName'),

            'username'  => env('DB_USERNAME', 'SomeUserName),

            'password'  => env('DB_PASSWORD', 'SomePassword'),         

        ],

So if you change any variable in .env file , it will get reflected in your application. No need to edit config file and change any credentials. :)

 

You may like: