I have read several posts/topics (like this, this and this) about the subject SaaS, Multi-Tenant, etc. and I reached the conclusion that most of them does not fit my requirements:
Workflow i need:
Example:
- project_admin <- Main database
--- subscriptions <- Table
------ id | db_name
------ 1 | project_child_one
------ 2 | project_child_two
--- users <- Table
------ id | subscription_id
------ 1 | 1
------ 2 | 2
- project_child_one <- Child database
--- customers <- table
- project_child_two <- Child database
--- customers <- table
user 1
login, the data retrieved from customers should be from database project_child_one
.user 2
login, the data retrieved from customers should be from database project_child_two
.I want the database name to be saved in the session so I don't need to always query the project_admin
in order to know in which database the user should connect to. This is the easy part.
If you really need to have a “tenant” database connection, then you can configure it on the fly in a middleware class:
class ConfigureTenantConnection
{
public function handle($request, Closure $next)
{
if ($user = $request->user()) {
// Create a tenant database connection if there is an authenticated user
config([
'database.connections.tenant' => [
'driver' => 'mysql',
// I don’t know what column names you use, but…
'host' => $user->database_host,
'port' => $user->database_port,
'database' => $user->database_name,
'username' => $user->database_username,
'password' => $user->database_password,
],
]);
}
return $next($request);
}
}
You can then use this tenant
connection in database queries and models:
abstract class TenantModel extends Model
{
protected $connection = 'tenant';
}
class Widget extends TenantModel
{
protected $table = 'widgets';
}
Well I am not sure whether this is what you meant . But if you want db name to be dynamic you can easily do it in the laravel as follows . The connections part of config should be like above . However you can change the database credential at the controller in the runtime . If we take the above example for the configuration then . You can do like this on the controller .
$config= [
'database'=>'Dynamic db name',
];
Config::set("database.connections.mysql2",$config);
DB::purge('mysql');
DB::setDefaultConnection('mysql2');
And suppose you want to switch another db after transaction you can do like this
$config= [
'database'=>'Dynamic db name',
];
Config::set("database.connections.mysql",$config);
DB::purge('mysql2');
DB::setDefaultConnection('mysql2');
I hope it helps