Working with .env(Environment) file in laravel 5

You can find this file as name of .env.example into the root folder of your application and can be renamed to .env and put it into local or production environment. This file will autoload by laravel.

In the below code two different environment file structures are defined.

1. Local .env file. This environment is using for local machine server.

// env file setup for local environment
APP_ENV = local
APP_DEBUG = true				// Enable debug errors
APP_KEY = SomeRandomString

DB_HOST = Your local machine name
DB_DATABASE = Sql Database Name
DB_USERNAME = Sql username
DB_PASSWORD = Sql password

 

2. Production .env file. Production environment is used when app is in server.

// env file setup for production environment
APP_ENV = production
APP_DEBUG = false				// Disable debug errors
APP_KEY = SomeRandomString

DB_HOST = server hostname
DB_DATABASE = Sql Database Name
DB_USERNAME = Sql username
DB_PASSWORD = Sql password

 

How to use environment variables?

We can use getenv(), A simple php function which returns the value of environment variables.

Use this in config/database.php file

<?php

'mysql' => [
	'driver'    => 'mysql',
	'host'      => getenv('DB_HOST'),
	'database'  => getenv('DB_DATABASE'),
	'username'  => getenv('DB_USERNAME'),
	'password'  => getenv('DB_PASSWORD'),
	'charset'   => 'utf8',
	'collation' => 'utf8_unicode_ci',
	'prefix'    => '',
	'strict'    => false,
]

Now, You will never need to change your 'mysql' driver settings in any environment.

Using getenv() in laravel blade : 

<!Doctype HTML>
<html>
<head>

@if(getenv('APP_ENV')=='production')    
    <script src="/js/app.min.js"></script>
@else
    <script src="/js/app.js"></script>
@endif

</head>
</html>

 

Something to say? Tell us in comment section.