Laravel Forge - Using Environment Variables for Environment Detection

Posted on May 19, 2014 | By Matt Stauffer


Warning: This post is over a year old. I don't always update old posts with new information, so some of this information may be out of date.

NOTE: This post has been completely re-written because of some changes in Forge's environment variable handling.

At any given point in your Laravel app's life, it'll have a particular "environment" defined, which is a string that identifies which environment (local, production, staging, etc.) you're running in. There are two hard-coded environments (production and testing) that have Laravel-specific meanings, but you can create as many as you want.

The ruleset you provide Laravel for detecting your environment happens in bootstrap/start.php. The default is to pass in an associative array, which allows you to change your environment based on your machine's hostname:

$env = $app->detectEnvironment(array(
    'local' => array('your-machine-name'),
));

You can also pass a Closure (anonymous function) to detectEnvironment. Our team at Tighten often uses Environment Variables:

$env = $app->detectEnvironment(function() {
    if (getenv('APP_NAME_ENV')) {
        return getenv('APP_NAME_ENV');
    } else {
        return 'local'; // Default
    }
});

Forge originally only stored its environment variables in .env.ENVIRONMENTNAMEHERE.php files, which cause problems with this method of environment detection. This is no longer the case.

However, based on some of my experiences with queues and other aspects of Forge, I'd still highly recommend you use the associative array form of environment detection rather than using a Closure. Try the following:

$env = $app->detectEnvironment(array(
    'production' => array('your-forge-staging-server-host-name-here'),
    'local' => array('homestead', '.local')
));

This means: Set the environment to "production" on my Forge server, set it to "local" if it's running on my Homestead vagrant VM, and set it to "local" if it's running locally on anyone's development machine (learn more about .local).


Comments? I'm @stauffermatt on Twitter


Tags: laravel  •  forge  •  environment