'Laravel - Get current .env() Value
I am working on a Laravel project. I often change the database connection between Mysql and Sqlite during development. In a php artisan Laravel command I have an import routine. Because I don't want to write the data into the wrong database, I want to set an if condition before the import. But unfortunately it doesn't work quite as I imagined.
if ( env('DB_CONNECTION', null ) === 'sqlite') {
// Import to sqlite
} else if (env('DB_CONNECTION') === 'mysql') {
// Import to mysql
} else {
// no database in env DB_CONNECTION
}
In my .env file currrently the DB_CONNECTION is set on sqlite. But env('DB_CONNECTION', null) returns null.
What do I have to do to find out the current connection? Maybe using env() is not the right choice at this point?
Solution 1:[1]
For all those who will have the same problem in the future. Always! But really always, after you have modified the .env variable, you should execute the following "cleaning" commands:
php artisan config:cache
php artisan config:clear
If you still don't get a value, ask SO.
Solution 2:[2]
- You should not use
env()function anywhere except config files. Instead, useconfig('database.default'), because when configuration is cached, the env is empty for security reasons. - You may create multiple database connections in
config/database.phpand switch between them manually using facade:DB::connection('sqlite'), orDB::connection('mysql')and avoid this uglyif - else iftree.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maik Lowrey |
| Solution 2 | PunyFlash |
