Best way to connect multiple databases in Laravel

I am creating an application with several tenants in which, based on the subdomain, I connect to the database of this particular tenant.

Here is the code for this:

// To connect with a subdomain - the entry will be in config/database.php. public static function connectSubdomainDatabase($dbname) { $res = DB::select("show databases like '{$dbname}'"); if (count($res) == 0) { App::abort(404); } Config::set('database.connections.subdomain.database', $dbname); //If you want to use query builder without having to specify the connection Config::set('database.default', 'subdomain'); DB::reconnect('subdomain'); } 

This is the best way to contact the database, or there is some kind of problem, because I think in terms of performance, because every time I connect to the database, when there are different subdomains. What is the best way to do this?

+5
source share
1 answer

This is the best way to do this. In the end, all this is an opinion. However, I would like to create a connection in the configuration file for each of the subdomains. Then, in your connectSubdomainDatabase () function, I would get the current subdomain instead of passing the database name. You can already specify the connection in laravel, the only place you should use the database names is in the configuration file.

So something like this:

 // To connect with a subdomain - the entry will be in config/database.php. public static function connectSubdomainDatabase() { // Break apart host $urlParts = explode('.', $_SERVER['HTTP_HOST']); // Change default connection Config::set('database.default', $urlParts[0]); } 

If the connections are config / database.php:

 'connections' => [ 'subdomain1' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], 'subdomain2' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', 'localhost'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', 'strict' => false, ], ], 
+1
source

Source: https://habr.com/ru/post/1233949/


All Articles