Skip to content

Instantly share code, notes, and snippets.

@spacemudd
Created December 3, 2020 09:44
Show Gist options
  • Save spacemudd/20d06141c1319517d2e651800bf9ae78 to your computer and use it in GitHub Desktop.
Save spacemudd/20d06141c1319517d2e651800bf9ae78 to your computer and use it in GitHub Desktop.
Middleware for automatic switch over of database host in Laravel
<?php
namespace App\Http\Middleware;
use Closure;
use Artisan;
use Log;
use DB;
class DrcSwitchMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
try {
DB::connection()->getPdo();
} catch (\Exception $e) {
DB::purge(config('database.default'));
if (str_contains(env('DB_HOST'), 'srv-itam')) {
Log::info('IS SWITCHING TO DRC');
$this->envUpdate('DB_HOST', env('DB_HOST_DRC'));
$this->envUpdate('DB_PORT',env('DB_PORT_DRC'));
} else {
Log::info('IS SWITCHING TO MAIN');
$this->envUpdate('DB_HOST', env('DB_HOST_MAIN'));
$this->envUpdate('DB_PORT',env('DB_PORT_MAIN'));
}
Artisan::call('config:clear');
exit('Please refresh');
}
return $next($request);
}
/**
* Update Laravel Env file Key's Value
* @param string $key
* @param string $value
*/
public function envUpdate($key, $value)
{
$path = base_path('.env');
if (file_exists($path)) {
file_put_contents($path, str_replace(
$key . '=' . env($key), $key . '=' . $value, file_get_contents($path)
));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment