Mike Classic

Laravel: App Environment Detection

When I develop Laravel apps, I do so in several different environments. As per the Laravel Docs, by default, the environment in which your app runs is defined in bootstrap/start.php as an array which maps hostnames of machines to whichever environments you want them to run.

You can make as many or as few environments as you want. It's recommended to create three separate environments, but again, there's no rule set in stone. These environments are: development, staging, & production. I used to have that set up as such:

$env = $app->detectEnvironment(array(
    'development' => array('vagrant-machine'),
    'staging' => array('staging.somehost.xyz'),
    'production' => array('www.yourapp.xyz')
));

One can also have multiple machine names mapped to an environment, so if you wanted to have two machines set up in your development environment, you could implement like so:

$env = $app->detectEnvironment(array(
    'development' => array('vagrant-machine', 'another-machine'),
    'staging' => array('staging.somehost.xyz'),
    'production' => array('www.yourapp.xyz')
));

It's a beautiful thing, being this simple and configurable.

Some people like to use environment variables so that they don't have to keep remembering a bunch of hostnames, especially if they deploy to multiple servers or instances. This can be accomplished by providing a Closure instead of an array to Laravel's $app->detectEnvironment() method:

$env = $app->detectEnvironment(function()
{
    return getenv('LARAVEL_ENV');
});

At this point, you could set your environment variable through Apache's .htaccess file:

SetEnv LARAVEL_ENV "development"

It's as simple as that.

Call me crazy, or stupid, but I actually have a mixture of both. If the environment variable has not been set, then fall back to the array of hostnames to determine environment.

$env = $app->detectEnvironment(function()
{
    // Set up the environments fall-back array
    $environments = array(
        'vagrant' => array('vagrant-box'),
        'local' => array('my-laptop')
    );

    // Attempt to determine via environment variable first
    $env = getenv('LARAVEL_ENV');
    if (!empty($env)) {
        return $env;
    } else {
        /*
         * Environment variable empty or invalid, proceed to sort
         * through fall-back hostname array
         */
        $hostname = gethostname();
        foreach ($environments as $environment => $hosts) {
            foreach ((array) $hosts as $host) {
                if (!strcasecmp($host, $hostname)) {
                    // Found, return mapped hostname, we're outta here
                    return $environment;
                }
            }
        }

        // Nothing matched, in array nor within environment veriable(s)
        return 'production';
    }
});
comments powered by Disqus