You use the env() method and the .env file. env() takes two arguments the envrinment variable you want to look up and the default if that variable doesn't exist.
So for example
$session_driver = env('SESSION_DRIVER','array');
In your .env file you would have
SESSION_DRIVER=file
So this means that $session_driver would be = file but if there was no entry in the .env file then $session_driver would be = array
So in your example of multiple DB connections
'mysql' => [
'driver' => 'mysql',
'host' => env('MYSQL_DB_HOST', 'localhost'),
'database' => env('MYSQL_DB_DATABASE', 'forge'),
'username' => env('MYSQL_DB_USERNAME', 'forge'),
'password' => env('MYSQL_DB_PASSWORD', ''),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => false,
],
'pgsql' => [
'driver' => 'pgsql',
'host' => env('PGSQL_DB_HOST', 'localhost'),
'database' => env('PGSQL_DB_DATABASE', 'forge'),
'username' => env('PGSQL_DB_USERNAME', 'forge'),
'password' => env('PGSQL_DB_PASSWORD', ''),
'charset' => 'utf8',
'prefix' => '',
'schema' => 'public',
]
In your .env file
MYSQL_DB_HOST=localhost
MYSQL_DB_DATABASE=foo
MYSQL_DB_USERNAME=bar
MYSQL_DB_PASSWORD=baz
PGSQL_DB_HOST=localhost
PGSQL_DB_DATABASE=baz
PGSQL_DB_USERNAME=bar
PGSQL_DB_PASSWORD=foo
There is a Laracast on the subject as well. https://laracasts.com/series/laravel-5-fundamentals/episodes/6
Thank you for your answer, it helped me a lot.
Although, I still find the old way cleaner.
Thanks, mikerh. That was very helpful!
How about Part A of thytanium's question? i.e. I want to use the mysql driver for prod and sqlite for testing (if I run phpunit, hit the sqlite db not otherwise). How does dotenv accomodate this? Do we need to add a conditional to the default key to make this happen?
Thanks!
Finally figured out a clean solution to the problem of wanting to use different db's for dev and testing in Laravel 5. In case anyone else is interested, here goes:
'default' => env('DATABASE_DRIVER','mysql'),
DATABASE_DRIVER=mysql
<env name="DATABASE_DRIVER" value="sqlite"/>
Essentially, what you are doing is setting prod and testing defaults for the key named "DATABASE_DRIVER" and then using whatever is set in database.php.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community