diff --git a/README.md b/README.md index ee80280..526ebdd 100644 --- a/README.md +++ b/README.md @@ -26,15 +26,25 @@ This will overwrite database connection values for `host`, `port`, `username`, ` ## Customization -Override that by publishing the config file and setting it's values in `config/db-uri.php`. +Override default behaviour by publishing the config file and setting values. -`php artisan vendor:publish --tag=db-uri` +`$ php artisan vendor:publish --tag=db-uri` +Set any database connections by supplying `default` or the key path, like `connections.pgsql`, or `redis` +to have a URL mapped onto the connection at that key path. + +config/db-uri.php ``` -// config/db-uri.php return [ - 'default' => 'DATABASE_URL', // default - 'mysql' => 'OTHER_MYSQL_URL', // custom override for the mysql driver + 'default' => 'SOME_DATABASE_URL', // "default" resolves key path from default key + 'connections.pgsql' => 'OTHER_PGSQL_URL', // Set the "pgsql" driver with different URL. Same when "default" set to "pgsql" + 'connections.mysql' => 'OTHER_MYSQL_URL', // Set the "mysql" driver with different URL ]; ``` +.env +``` +DATABASE_URL=postgresql://username:password@localhost:5432/database-name +OTHER_MYSQL_URL=mysql://username:password@localhost:3306/db_example +``` + diff --git a/src/LaravelDbUriServiceProvider.php b/src/LaravelDbUriServiceProvider.php index 9cab4b5..de37da6 100644 --- a/src/LaravelDbUriServiceProvider.php +++ b/src/LaravelDbUriServiceProvider.php @@ -44,20 +44,23 @@ public function register() $connections = config('db-uri'); // Loop and set each connection - foreach($connections as $driver => $connection_key) { + foreach($connections as $driver_path => $connection_key) { // If "default" driver, look up the value for the actual connection - $driver = $driver === 'default' ? config('database.default') : $driver; + // "default" resolves to something like "connections.pgsql" + $driver_path = $driver_path === 'default' ? 'connections.' . config('database.default') : $driver_path; // Get the DATABASE_URL env value or skip out - if(empty($url = env($connection_key))) return; + if(empty($url = env($connection_key))) continue; // Try to parse it if(!$components = parse_url($url)) throw new \Exception('Database URL may be malformed.'); // Set each config foreach($this->config_map as $component_key => $config_key) { - config(["database.connections.{$driver}.{$config_key}" => $this->clean($component_key, $components[$component_key])]); + // Skip setting when no value + if(empty($components[$component_key])) continue; + config(["database.{$driver_path}.{$config_key}" => $this->clean($component_key, $components[$component_key])]); } } }