Home > Software design >  Laravel - Get current .env() Value
Laravel - Get current .env() Value

Time:04-13

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?

CodePudding user response:

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.

CodePudding user response:

  1. You should not use env() function anywhere except config files. Instead, use config('database.default'), because when configuration is cached, the env is empty for security reasons.
  2. You may create multiple database connections in config/database.php and switch between them manually using facade: DB::connection('sqlite'), or DB::connection('mysql') and avoid this ugly if - else if tree.
  • Related