Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

cron - Configure database connections on the fly in Laravel

In Laravel 8, I am trying to set dynamic connections in two scenarios:

  1. 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.

  1. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...