-
-
Save ajcastro/0f4900ea4a35b3ecb40754e476ebe3b4 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