Detecting Environment in Laravel 4

Update: How to Get Environment in Laravel 5

Your PHP application should have different settings for its development and production environments. Here’s how you can set your Laravel 4 app to detect the environment, load the appropriate settings and keep installation-specific things like database credentials out of your Git repo.

Detecting The Environment

Laravel lets you provide arrays of hostnames it will check the server against to determine the environment.

Open bootstrap/start.php

$env = $app->detectEnvironment([
   'local' => ['MyMachineName', 'AnotherDevMachine'],
   'staging' => ['StagingEnvName']

If unsure, use PHP’s gethostname() function to find your machine names.
This is the value to use inside the local/staging arrays

Laravel will default to ‘production’ if no other environment is matched.


Setting Environment Config Values

Laravel looks for .env.*.php files in the root directory (beside your composer.json and .gitignore files).

You will want to exclude these files from your Git repo. Add the following lines to your .gitignore


Then create an env file for each of your environments. Use .env.php for the production environment.
They should look something like this:


 * Local Development
 return array(
	'app.env'		=> 'dev',
	'app.debug'		=> true,
	'app.url'		=> '',

	''	 => '',
	'mysql.database' => 'bestDbEva',
	'mysql.username' => 'me',
	'mysql.password' => 'myTremendousPassword'


The actual values are up to you. You can store whatever values you need within the application.

Using The Environment Values

Laravel config can now call getenv() to get the dynamic environment variable. For your DB config open app/config/database.php

'mysql' => array(
	'driver'    => 'mysql',
	'host'      => getenv(''),
	'database'  => getenv('mysql.database'),
	'username'  => getenv('mysql.username'),
	'password'  => getenv('mysql.password'),
	'charset'   => 'utf8',
	'collation' => 'utf8_unicode_ci',
	'prefix'    => '',

One thought on “Detecting Environment in Laravel 4

  1. Pingback: Laravel 5 getenv

Leave a Reply

Your email address will not be published. Required fields are marked *