I wanted to create a multi tenant database based application here’s the flow:
There is one database known as “myGlobalDatabaseName” where it has users table.
Now when a user logins the database name is fetched from the users table lets say “user1Database”
Now when in dashboard i want to access the Products table that is inside the user1Database and also want the user information from globalDatabase
I could not find any way to create a Model for Products and Model For User where it can switch the database when specific model is called like when i do Products:all() it should give me the data from products table but of private db
for Now i Have been doing this way
Making two function in controller and using them like
public function privateDB(string $exceptional_identifier = ""): Connection
{
if(!empty($exceptional_identifier))
{
$exceptional_identifier = "";
}
if (empty($exceptional_identifier)) {
$request = Request::instance();
$database_identifier = $request->cookie("selected_company_id");
$database_identifier = $this->globalDB()->table(TableLists::COMPANIES)->where("id", $database_identifier)->first();
$exceptional_identifier = $database_identifier->company_identifier;
}
Config::set('database.connections.private.database', env("DB_QFIX") . $exceptional_identifier);
return DB::connection('private');
}
/**
*
* Global Database
*
* @return Connection
*/
public function globalDB(): Connection {
return DB::connection('global');
}
and when ever i want i would use this like:
$products = $this->privateDB()->table("products")->get();
$users = $this->globalDB()->table("users")->get();