Recently I'm working on a laravel which is a shop management system, where every shop will have its own database. User have access database connection access from session after login. But I can't establish this system by own.
Asked
Active
Viewed 2,043 times
2 Answers
2
For an application similar to this, I have a tenants database and table where I store the subdomains and connection data for each tenant.
Then, I built a Middleware like this:
<?php
namespace App\Http\Middleware;
use Config;
use Closure;
use App\Models\Tenant;
class SubdomainSetup
{
public function handle($request, Closure $next)
{
$subdomain = $request->server()['HTTP_HOST'];
$tenant = Tenant::where('subdomain', $subdomain)->firstOrFail();
config([
'database.connections.mysql.tenantid' => $tenant->tenantid,
'database.connections.mysql.host' => $tenant->host,
'database.connections.mysql.database' => $tenant->database,
'database.connections.mysql.username' => $tenant->username,
'database.connections.mysql.password' => $tenant->password,
]);
return $next($request);
}
}
and add it to my global Kernel.php
protected $middleware = [
.....
\App\Http\Middleware\SubdomainSetup::class,
];
so every request goes through this setup first. That way, you set up your connection transparently based on the subdomain name.
Easy, clean and secure.

JoeGalind
- 3,545
- 2
- 29
- 33
-
It is not multi domain system. – Nihar Ranjan Das Nov 09 '20 at 07:55
1
One way to change connection at runtime is to set the values via the config:
config(['database.connections.mysql_new_connection' => [
'driver' => 'mysql',
'host' => env('DB_HOST', 'localhost'),
'database' => env('DB_DATABASE', 'database_name'),
'username' => env('DB_USERNAME', 'user_name'),
'password' => env('DB_PASSWORD', 'password'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci'
]]);
then you can specify a connection via the DB facade:
DB::connection('mysql_new_connection')->select('');

Mustafa Poya
- 2,615
- 5
- 22
- 36