May 19, 2014 | laravel, forge, environment

Laravel Forge - Using Environment Variables for Environment Detection


This is a series of posts on Laravel Forge.

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

This is part of a series of posts on Laravel Forge:

  1. May 16, 2014 | forge, laravel, papertrail
  2. May 23, 2014 | laravel, forge, queue, beanstalkd
  3. Jun 2, 2014 | laravel, forge, cron
  4. Jun 2, 2014 | forge, laravel, ssl
  5. Jun 17, 2014 | forge, htpasswd, nginx
  6. Jun 23, 2014 | laravel, forge, subdomains
  7. Jul 9, 2014 | forge, laravel, recipes
  8. Jul 25, 2014 | laravel, forge, aws, hosting
  9. Sep 17, 2014 | laravel, forge
  10. Dec 24, 2014 | forge, sculpin, fiveMinuteGeekShow


For quick links to fresh content, and for more thoughts that don't make it to the blog.