Skip to content
This repository was archived by the owner on Apr 15, 2025. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
```


11 changes: 7 additions & 4 deletions src/LaravelDbUriServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -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])]);
}
}
}
Expand Down