In Laravel 8, I am trying to set dynamic connections in two scenarios:
- After login, depending on the user I set a custom database connection.
In this case, after login, in a middleware I call a method:
public static function changeConnection($customerId)
{
$database = Database::where('customer_id', '=', $customerId)->first();
if (empty($database)) {
return null;
}
$connectionName = 'customer';
$config = Config::get('database.connections.' . $connectionName);
$config = [
'driver' => 'mysql',
'host' => $database->database_host,
'port' => $database->database_port,
'database' => $database->database_name,
'username' => $database->database_username,
'password' => $database->database_password
];
config()->set('database.connections.' . $connectionName, $config);
DB::purge($connectionName);
return $connectionName;
}
This works perfect, and the connection works perfectly.
- I need to run some processes in a job. So I need to access each user database, I tried to do the same process, but I keep getting an error:
local.ERROR: SQLSTATE[HY000] [2002] No such file or directory (SQL:
select ... is null) {"exception":"[object]
(IlluminateDatabaseQueryException(code: 2002): SQLSTATE[HY000]
[2002] No such file or directory (SQL: select ... is null) at
/app/vendor/laravel/framework/src/Illuminate/Database/Connection.php:671)
Any ideas?, I guess inside a job, since it runs in console, the procedure is different?
question from:
https://stackoverflow.com/questions/65907953/configure-database-connections-on-the-fly-in-laravel 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…