Laravel - custom .env file

前端 未结 6 1892
难免孤独
难免孤独 2020-12-31 19:41

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 f

6条回答
  •  没有蜡笔的小新
    2020-12-31 20:23

    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.

提交回复
热议问题