2

I am building an application where I need to work on two git branch. For two branch, I need to maintain two database and every time I checkout to another branch I need to manually change database from .env file. (env file is included in .gitignore file)

Is there any way to access config variables from env? I tried this below way:

DB_DATABASE="${config('database.database')}"

But it is not working.

Note: I could do it by changing in config/database.php but I am in restriction that's why trying to find another way.

Manzurul Hoque Rumi
  • 2,911
  • 4
  • 20
  • 43
  • 2
    This is built to work the other way around, because an environment specific values need to be used by the configuration. The connection to the database reads from the `config` files, not directly from the `.env` file. That's why for example if you don't have `DB_DATABASE` in your `.env` file, it will still try to connect to a default database. – nakov Jun 25 '19 at 06:46
  • @nakov I know but I can't change `config` file.(Restriction) – Manzurul Hoque Rumi Jun 25 '19 at 06:48
  • Then look at [this answer](https://stackoverflow.com/a/43731580/1457270), this is the best approach I think. – nakov Jun 25 '19 at 06:54

3 Answers3

2

Instead of modifying the .env you could make multiple versions of your config/database.php where you simply enter the database settings instead of using the env:

old:

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),

new:

'mysql' => [
            'driver' => 'mysql',
            'host' => '123.123.123.123',

You can then proceed to make stashes in your GIT, and simply apply the correct one depending on the branch you are on.

Bram Verstraten
  • 1,414
  • 11
  • 24
0

Another approach would be to have multiple .env files that contain the branch in the file name.

  • .env.production
  • .env.development

Don't forget to add these files to your .gitignore!

When switching branches you can manually change the name of the corresponding .env.<branchname> back to .env.

Bram Verstraten
  • 1,414
  • 11
  • 24
0

I've worked up a solution for you. I tried it on my environment and it works as you expect.

So in addition to what @Bram said, you can create branch specific .env files.

.env.master and .env.develop for example. Add both to .gitignore.

Then create a git post-checkout hook:

vim .git/hooks/post-checkout

With the following content:

#!/bin/bash

printf '\npost-checkout hook\n\n'
BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)
cp .env.$BRANCH_NAME .env

Add permissions to the file:

chmod u+x .git/hooks/post-checkout

Now when you checkout your develop branch the content of the .env file will be from .env.develop and same for master. This is the most automated way unless you want to extend the Illuminate\Foundation\Application file and change the

protected $environmentFile = '.env';

that way.

nakov
  • 13,938
  • 12
  • 60
  • 110