Reputation: 13
I going to use dynamic database connections in backend.
Config::set('database.connections._pgsql.host', $connection->host);
Config::set('database.connections._pgsql.port', $connection->port);
Config::set('database.connections._pgsql.username', $connection->account_name);
Config::set('database.connections._pgsql.password', $connection->password);
Config::set('database.connections._pgsql.database', $connection->initial_db);
DB::purge('_pgsql');
DB::reconnect('_pgsql');
As you see, I have to change db config every request to use dynamic db connections. If there are concurrent requests with different db connections then how can I handle these requests and connections?
Please help me.
Upvotes: 1
Views: 3567
Reputation:
The documentation is good for a lot of situations, however, I find it to be more convenient in a lot of situations to set the connection in middleware. This is more tailored for multi-tenancy type apps but it may be useful for you:
public function handle($request, Closure $next)
{
// if a user belongs to an organization, company, team, etc.
// and each having their own database with a DSN stored in the database.
if (auth()->check() && auth()->user()->company->active) {
$uuid = $request->user()->company->db_uuid;
$host = $request->user()->company->db_host;
// here you can merge additional connection info in, such
// as a master password from .env, for example
$password = config('database.customer.master');
// then set the default connection or assign a new one
config(['database.connections.customer' => [
'host' => $host,
'password' => $password,
'database' => $uuid,
'username' => 'customer_master'
]]);
return $next($request);
}
abort(403, 'Unauthorized');
}
Every query from there on in the request lifecycle will use that connection, without the need to set the connection each time.
Most of the models were specific to customer needs so we set the database connection in a base model and inherited where needed.
class BaseModel extends Model
{
public function __construct($attributes = []) {
parent::__construct($attributes);
$this->connection = config('database.connections.customer');
}
}
Upvotes: 3
Reputation: 1167
The configuration for your application is static unless changed via the files itself or .env.
If you wish to separate the database per user, you can store the connection name in the session instead.
An example:
$users = DB::connection(session('databaseName'))->select(...);
In your login action, you should set the session: session(['databaseName' => 'secondDatabase']);
Make sure that in your database.php
that you have a connection called 'secondDatabase'.
Upvotes: 0