Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - custom .env file

Tags:

php

laravel

Laravel assumes that .env file should describe environment, and it should not be committed to your repo.

What if I want to keep both .env files for dev and production (say .env-production and .env-dev) in my repo and add some custom logic to which file should be used, for example based on current domain name.

Something like

if ($_SERVER['HTTP_HOST'] == 'prod.domain.com') {
    load('.env-production');
} else {
    load('.env-dev');
}

How can i achieve it? Thanks!

like image 284
SmxCde Avatar asked Aug 08 '16 07:08

SmxCde


2 Answers

I have similar requirements during development, and wanted to do some ad-hoc 'multitenancy' on my dev box to test the same codebase against multiple databases/configurations. I didn't want spaghetti code with a bunch of if/then statements, so I came up with the following solution, which works great for my purposes (and doesn't require any mucking about with Apache, nginx or Caddy files):

Add the following in bootstrap/app.php right after the $app = new Illuminate\Foundation\Application(...); lines:

// First, check to see if there is a file named '.env'
// within a subdirectory named '.env.{{HOST_NAME}}
//
if (is_file($app->environmentPath().DIRECTORY_SEPARATOR. '.env.' . $_SERVER['HTTP_HOST'] .DIRECTORY_SEPARATOR. '.env')) {

    // ...And if there is, use the directory as the new environment path
    $app->useEnvironmentPath($app->environmentPath().DIRECTORY_SEPARATOR. '.env.'. $_SERVER['HTTP_HOST']);
}ER['HTTP_HOST']);
}

// Otherwise,  just use the standard .env file as the default...

Once this is included, the app will still use .env by default (meaning you can still use the standard .env file for any hosts that don't require customization), but first it checks to see if an alternative .env file exists within a subdirectory named after the hostname (ie, if the hostname is 'example.local.com', the file would reside within a subdirectory named .env.example.local.com).

You could change the code to remove the somewhat redundant .env. prefix from the directory name, but I like to add it to keep all the .env.* entries together in directory listings.

One bonus of this approach: By using the usual name ('.env') within subdirectories, you should only need a single entry of .env to ensure all your custom configurations stay out of your git repo. No need to add a new .gitignore entry for each custom dot-env file.

like image 97
Mike Fahy Avatar answered Sep 20 '22 05:09

Mike Fahy


Nadeem0035 gave me pretty good idea what to do

bootstrap\app.php right before return $app;

$envFile = $_SERVER['HTTP_HOST'] == 'prod.domain.com' ? '.env-production' : '.env-dev';
$app->loadEnvironmentFrom($envFile);
like image 26
SmxCde Avatar answered Sep 20 '22 05:09

SmxCde