Reputation: 1
I have a simple multitenancy logic in Laravel, it works like this:
To achieve this, I have overriden the DatabaseManager and DatabaseServiceProvider, and changed the "connection" method to check the subdomain, like the code below.
Basically it works perfectly with nginx, and my project is running for years without problems.
The issue is: I'm developing a websocket on this project, and for that I'm using Laravel Swoole. I configured my nginx to be only the proxy for the project, and the websocket is working, but when I tested the multitenancy it doesn't work.
Laravel Swoole seems to read the first configuration and then it doesn't change anymore.
Explaining my approach to multitenancy: With older versions of Laravel I had a simpler approach that was only a middleware that did the same thing, on newer ones (I'm using Laravel 8 on this project) I had to do this, because I couldn't get the Middleware approach was to work, it seemed to open connection to the database before reaching the middleware, so I configured on the "root". I'm explaining this because I'm not sure if this is the problem, and if there is a more correct approach for doing this. I tried to read some of the open source solutions, but it was too complicated for my needs.
This is basically the code:
class CustomDatabaseManager
{
private function getSubdomain()
{
return explode('.', parse_url(request()->url(), PHP_URL_HOST))[0];
}
public function connection($name = null)
{
[$database, $type] = $this->parseConnectionName($name);
$name = $name ?: $database;
if ($name == 'tenant')
{
$subdomain = $this->getSubdomain();
$tenant = Tenant::where('referencia', $subdomain)->first();
if ($tenant != null)
{
$this->app['config']["database.connections.tenant.database"] = $tenant->pgsql_bd;
}
}
// If we haven't created this connection, we'll create it based on the config
// provided in the application. Once we've created the connections we will
// set the "fetch mode" for PDO which determines the query return types.
if (! isset($this->connections[$name])) {
$this->connections[$name] = $this->configure(
$this->makeConnection($database), $type
);
}
return $this->connections[$name];
}
}
I've tried:
I've also tried:
I just want to change the connection and read the second database.
Upvotes: 0
Views: 116