Laravel dynamically detect environment

Laravel 5.2 comes with a .env file and tells you to not check it in. The idea behind it, is that you will have another .env file on your development, testing and production server. But if you want to dynamically detect and set your environment, this does not work too well. To make dynamically detection and setting possible, use the detectEnvironment() method of the Application class.

Create a new file in bootstrap directory for example environment.php:

$env = $app->detectEnvironment(function() {
  // Add your logic, for example:
  switch ($_SERVER['HTTP_HOST']) {
    case 'mytestserver.com':
      // required file for examples defines APP_KEY constant
      return 'testing';
      return 'production';

putenv('APP_ENV=' . $env);
putenv('APP_KEY=' . APP_KEY);

Make sure this file loads by requiring it in the bootstrap/app.php file:

require __DIR__ . '/environment.php';
Tag: , | Category: