2

I use Laravel 5.3. I have defined my connection to my DB in my env file.

I work with several MySQL server, if one is down, I want to automaticly use a 2nd connection.

I will use the filters I think and catch a PDOException.

But I want to know if Laravel have a better approach to do this, I would like to only use config / env.

1 Answer 1

4

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

This a good approach ! This is what I wanted to do, by catching a PDO Exception. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.