Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting multiple sets of environment variables in Laravel 5

Edit: This question orignally applied to testing, but essentially I'd like to know if it's possible to have more than one .env file that can define multiple sets of environment variables; much like how L4 did it with env.local.php, env.testing.php etc


I'm using Laravel 5 and developing on homestead box.

I have my .env file populated with my local environment variables (mysql database etc).

I wish to use an sqlite database for testing so I added some variables to phpunit.xml so it looks like this:

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="DB_DRIVER" value="sqlite" />
    <env name="DB_PATH" value="database.sqlite" />
</php>

All the appropriate environment variables are referenced in the config files e.g. env('DB_DRIVER').

Yet, when I try to migrate the database using php artisan migrate --env=testing I get "nothing to migrate" suggesting Laravel is trying to migrate my local (mysql) database (which is already migrated).

I decided to explore further via tinker, so I ran php artisan tinker --env=testing. Within tinker I ran app()->environment(); which returned "testing". So far so good!

Next I echoed out the env variables via $_ENV, and it returned my local environment variables, despite the environment being set to testing.

Why is this? It seems Laravel is ignoring the phpunit.xml env variables and just using the .env file regardless...

Edit

It seems laravel only uses the phpunit.xml file if run via phpunit itself, even if the environment is set to testing separately.

If anyone knows how to set multiple environments in L5 I'm appreciate it as the L4 way of just making a .env.testing file doesn't work.

like image 307
harryg Avatar asked Apr 21 '15 21:04

harryg


1 Answers

A quick workaround for the original question, just the testing environment case, is to call $this->artisan('migrate'); from tests/TestCase.php class, so it will get the database configuration values defined in phpunit.xml and perform the migration.

like image 69
marcanuy Avatar answered Oct 04 '22 21:10

marcanuy