0

I want to change the database connection dynamically. I have created middleware for changing database connections. it works on API routes. But it does not work on the web routes.

below middleware code:

public function handle($request, Closure $next)
    {
        $cookie_name = 'x-connection-object';
        if(!empty($_COOKIE[$cookie_name])) {
            $connection = trim($_COOKIE[$cookie_name]);
            $db = strlen($connection) ? $connection : 'test213';
            \Config::set('database.default', 'mysql');
            $user = User::where('code', 'like', $db)->first();
            if($school) {
                \Config::set('database.default', $user->connection_name);
            } else {
                $error['institute_code'][]='Please Check Code';
                return response()->json(['errors'=>$error],422);
            }
        }
        return $next($request);
    }

I checked Database Name while running it shows the old database name it does not show the new database name.

1 Answer 1

1

use below code in Middleware

\Illuminate\Support\Facades\DB::setDefaultConnection('connection1');

and for another connection

\Illuminate\Support\Facades\DB::setDefaultConnection('connection2');
Sign up to request clarification or add additional context in comments.

Comments

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.