When using middlewares, you can try/catch the exceptions in your request and then switch your connection. Not sure if this will work with consoles or migration. Probably not.
Add this middleware in your 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 a proper exception here, depending on which way/database you are connecting
$this->switchConnection();
return $next($request);
}
}
private function switchConnection()
{
//here get all connections from config that applies
//@todo use a better way to get those db names
$dbNames = ['conn1', 'conn2', 'conn3',];
foreach($dbNames as $dbName) {
try {
\DB::connection($dbName)->getDatabaseName();
\Config::set('database.default', $dbName);
return;
} catch (\Exception $e) {
continue;
}
}
}
}
Add in your Kernel.php
protected $routeMiddleware = [
...
'switchConnection' => \App\Http\Middleware\SwitchConnection::class,
Then in your routes.php you can do like this:
Route::group('middleware' => ['switchConnection']], function(){
.... //your routes go here
});