Created
December 15, 2023 14:15
-
-
Save brasizza/0f5d50498031315323622d2b979abbd0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
use Illuminate\Support\Facades\DB; | |
use Illuminate\Support\Facades\Schema; | |
/** | |
* | |
*/ | |
class DatabaseConnection | |
{ | |
/** | |
* Change the database connection in a Laravel application. | |
* | |
* @param array|null $databaseData The database connection details. | |
* @return void | |
*/ | |
public static function changeDatabase(?array $databaseData): bool | |
{ | |
try { | |
if ($databaseData === null) { | |
return false; | |
} | |
if($databaseData['flg_cloud'] == 0 ){ | |
return self::changeDatabasePremisse(); | |
} | |
config([ | |
'database.connections.tenant' => [ | |
'driver' => 'mysql', | |
'host' => $databaseData['hostDB'], | |
'port' => $databaseData['portDB'], | |
'database' => $databaseData['bancoDB'], | |
'username' => $databaseData['usuarioDB'], | |
'password' => $databaseData['senhaDB'], | |
'charset' => 'utf8mb4', | |
'collation' => 'utf8mb4_unicode_ci', | |
'prefix' => '', | |
'strict' => false, | |
'engine' => null, | |
], | |
'database.default' => 'tenant', | |
]); | |
DB::purge('tenant'); | |
DB::purge('mysql'); | |
Schema::connection('tenant')->getConnection()->reconnect(); | |
return true; | |
} catch (\Throwable $e) { | |
return false; | |
} | |
} | |
public static function changeDatabasePremisse(): bool | |
{ | |
try { | |
config([ | |
'database.connections.tenant' => [ | |
'driver' => 'mysql', | |
'host' => '127.0.0.1', | |
'port' => 3306, | |
'database' => 'epoc3', | |
'username' => 'epoc2', | |
'password' => 'p0c2p0c2', | |
'charset' => 'utf8mb4', | |
'collation' => 'utf8mb4_unicode_ci', | |
'prefix' => '', | |
'strict' => false, | |
'engine' => null, | |
], | |
'database.default' => 'tenant', | |
]); | |
DB::purge('tenant'); | |
DB::purge('mysql'); | |
Schema::connection('tenant')->getConnection()->reconnect(); | |
return true; | |
} catch (\Throwable $e) { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment