2017-06-17 19:48:31 -05:00
|
|
|
<?php
|
|
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
namespace App\Extensions;
|
2017-06-17 19:48:31 -05:00
|
|
|
|
2024-03-12 22:39:16 -04:00
|
|
|
use App\Models\DatabaseHost;
|
2017-06-17 19:48:31 -05:00
|
|
|
|
|
|
|
|
class DynamicDatabaseConnection
|
|
|
|
|
{
|
2021-01-23 12:33:34 -08:00
|
|
|
public const DB_CHARSET = 'utf8';
|
2024-10-19 18:29:44 -04:00
|
|
|
|
2021-01-23 12:33:34 -08:00
|
|
|
public const DB_COLLATION = 'utf8_unicode_ci';
|
2024-10-19 18:29:44 -04:00
|
|
|
|
2021-01-23 12:33:34 -08:00
|
|
|
public const DB_DRIVER = 'mysql';
|
2017-06-17 19:48:31 -05:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Adds a dynamic database connection entry to the runtime config.
|
|
|
|
|
*/
|
2022-10-14 10:59:20 -06:00
|
|
|
public function set(string $connection, DatabaseHost|int $host, string $database = 'mysql'): void
|
2017-06-17 19:48:31 -05:00
|
|
|
{
|
2021-01-23 12:33:34 -08:00
|
|
|
if (!$host instanceof DatabaseHost) {
|
2024-03-16 22:41:36 -04:00
|
|
|
$host = DatabaseHost::query()->findOrFail($host);
|
2017-06-17 19:48:31 -05:00
|
|
|
}
|
|
|
|
|
|
2024-10-19 21:14:41 -04:00
|
|
|
config()->set('database.connections.' . $connection, [
|
2017-06-17 19:48:31 -05:00
|
|
|
'driver' => self::DB_DRIVER,
|
|
|
|
|
'host' => $host->host,
|
|
|
|
|
'port' => $host->port,
|
|
|
|
|
'database' => $database,
|
|
|
|
|
'username' => $host->username,
|
2024-05-28 15:24:20 +02:00
|
|
|
'password' => $host->password,
|
2017-06-17 19:48:31 -05:00
|
|
|
'charset' => self::DB_CHARSET,
|
|
|
|
|
'collation' => self::DB_COLLATION,
|
|
|
|
|
]);
|
|
|
|
|
}
|
|
|
|
|
}
|