Last active
July 10, 2018 03:34
-
-
Save aindong/1b6cf65a58b4d71e3fc7acb83452f7a2 to your computer and use it in GitHub Desktop.
Multi-Tenant Middleware Laravel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Http\Middleware; | |
use Closure; | |
use Illuminate\Config\Repository as Config; | |
class TenantDetector { | |
protected $config; | |
public function __construct(Config $config) | |
{ | |
$this->config = $config; | |
} | |
/** | |
* Handle an incoming request. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @param \Closure $next | |
* @return mixed | |
*/ | |
public function handle($request, Closure $next) | |
{ | |
$tenant = 'dev'; | |
\Log::info($request->header('authorization')); | |
if ($request->header('authorization') || $request->has('access_token')) { | |
$clientId = \Authorizer::getClientId(); | |
$client = \DB::connection('mysql2')->table('oauth_clients') | |
->where('id', $clientId)->first(); | |
$tenant = $client->tenant; | |
} | |
// \Log::info('Tenant Request: '. $tenant); | |
$this->updateDatabase($tenant); | |
// add tenant | |
$request->attributes->add(['tenant' => $tenant]); | |
return $next($request); | |
} | |
/** | |
* Update database configuration | |
* | |
* @param $tenant | |
* @return bool | |
*/ | |
private function updateDatabase($tenant) | |
{ | |
$dbName = 'saas_'; | |
$default = $this->config->get('database.connections.mysql'); | |
if (empty($tenant)) { | |
\Log::info('Using database: '.$dbName.'test'); | |
$default['database'] = $dbName.'test'; | |
return true; | |
} | |
$default['database'] = $dbName.$tenant; | |
$this->config->set('database.connections.dynamic', $default); | |
\Log::info('Using database: '.$this->config->get('database.connections.dynamic.database')); | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment