php - Automatically connect to another database if failed in Laravel 5.3 -


i use laravel 5.3. have defined connection db in env file.

i work several mysql server, if 1 down, want automaticly use 2nd connection.

i use filters think , catch pdoexception.

but want know if laravel have better approach this, use config / env.

when using middlewares, can try/catch exceptions in request , switch connection. not sure if work consoles or migration. not.

add middleware in application:

namespace app\http\middleware;  use closure; use db;  class switchconnection {     public function handle($request, closure $next)     {         try {             return $next($request);         } catch (\exception $e) { //use proper exception here, depending on way/database connecting             $this->switchconnection();             return $next($request);         }     }      private function switchconnection()     {         //here connections config applies         //@todo use better way db names         $dbnames = ['conn1', 'conn2', 'conn3',];         foreach($dbnames $dbname) {             try {                 \db::connection($dbname)->getdatabasename();                 \config::set('database.default', $dbname);                 return;             } catch (\exception $e) {                 continue;             }         }     } } 

add in kernel.php

protected $routemiddleware = [     ...     'switchconnection' => \app\http\middleware\switchconnection::class, 

then in routes.php can this:

route::group('middleware' => ['switchconnection']], function(){ .... //your routes go here }); 

Comments

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -