Search code examples
phplaravel-5phpdotenv

Laravel 5 - Environment Detection by Server Name


I understand with Laravel 5, it uses .env files so we can set specific enivornment values.

My question is, is there a way in Laravel 5, to say for example,

if ($SERVER_NAME == "my_production_server") {
    $environment = "production"
}

And from that it uses production values. My thinking is, I'd like all the environments and their variables placed in one file or directory, or whatever so we can deploy the whole build without any manual intervention, and we can check this all into our code repository.


Solution

  • Laravel 5 has made this a little harder than before but here's the way to do it. All you will need to do after this is change a value of your .env file and the environment will change

    The steps to do this are as follows

    1. Look at your local .env installed by Laravel and change its contents to local or production or whatever else you need

    2. Create 2 files .local.env and .production.env

    3. Add default environment value:

      • In .local.env : APP_ENV=local
      • In .production.env : APP_ENV=production
    4. Create new php file and named it, environment.php, save it into this folder: app/bootstrap/environment.php

      $env = $app->detectEnvironment(function(){
        $environmentPath = __DIR__.'/../.env';
         $setEnv = trim(file_get_contents($environmentPath));
         if (file_exists($environmentPath)){
                putenv("APP_ENV=$setEnv");
                if (getenv('APP_ENV') && file_exists(__DIR__.'/../.' .getenv('APP_ENV') .'.env')) {
                     Dotenv::load(__DIR__ . '/../', '.' . getenv('APP_ENV') . '.env');
                } 
         }
      });
      
    5. Include your environment.php file in bootstrap file. Paste it inside your bootstrap/app.php file.

      require __DIR__.'/environment.php';
      

    Yay! You're done.

    NOTE: If Laravel can't find a .env file it automatically uses .production.env which makes it awesome for deployments

    Credit to http://developers.ph/laravel-framework/laravel-5/how-to-setup-multiple-environment-for-laravel-5-developers-way/