Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

SachinAgarwal's avatar

[L5] Change Default Database connection Dynamically.

I want to set the default database connection dynamically.

Config::Set() will do it for 1 request only. I want it for every subsequent request.

I can do it by storing it in session, and do the Config::set() for every request. But that is not the efficient way for my application.

I have a logic but i dont know how to implement it.
Logic is to set the environment variable dynamically. But i don't know how to do it?

0 likes
18 replies
SachinAgarwal's avatar

I have set of organizations as client. And each client have a separate database. so after logging in, I will change the db according to the client (Organization)

SachinAgarwal's avatar

@blackbird Ya I know about this, But I have same model for all organizations, so i will be using same model everywhere. So this will not meet the needs of me.
And yea, setting Environment variable will also not help.
So Far The Best solution is to change the default database connection for every request.

Marlon's avatar

I have a system where I need to change my connection dynamically in my main database I have a table with the parameters for other databases (some times in other servers) Then I do

$nameKey = 'NameOfConnection';

$dataSync = AtlasBases::find($id_client);

Config::set('database.connections.' . $nameKey, array(
        'driver'    => 'mysql',
        'host'      => $dataSync->site_db_server,
        'database'  => $dataSync->site_db_base,
        'username'  => $dataSync->site_db_user,
        'password'  => $dataSync->site_db_password,
            'charset'   => 'utf8',
        'collation' => 'utf8_general_ci',
        'prefix'    => '',
));
# And set the new connection to my models

$imobModel = new ImobImoveis;
$imobModel->setConnection($nameKey);

Very simple, but works nice to me

Hope I can help you

3 likes
SachinAgarwal's avatar

@uxweb I did it with similar logic, But i did not create a package for api, i just retrieve my databases name from a table, and set the name of the database for the connection. Your solution helped me making this logic, thanks :D

juan's avatar

Hello Sachin, do you mind sharing your solution ? I am stuck on the same problem, and \Config::set() is not taking me anywhere; only for that one request.

vinodmot's avatar

Set database connections in your config/database.php :

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST'),
        'port' => env('DB_PORT'),
        'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql2' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST'),
        'port' => env('DB_PORT'),
        'database' => env('DB_DATABASE'),
        'username' => env('DB_USERNAME'),
        'password' => env('DB_PASSWORD'),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

],

Create middleware setDB:

namespace App\Http\Middleware;
use Cookie;
use Config;
use Closure;
use DB;
use App\User;
use Auth;
use Session;
class SetDB
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if($request->has('auth_token') || Session::has('auth_token')){
            if($request->has('auth_token')){
                $token=$request->get('auth_token');
                $result=DB::connection('mysql2')->table('mst_editor_database_info')->where("auth_token",$token)->first();
                DB::disconnect(env('DB_DATABASE'));
                if($result == null ) {
                    Auth::logout();
                    Session::flush();
                    return redirect('/');
                    //return redirect('http://www.webtart.com');
                }else{
                    if($result->is_first==1){
                        DB::connection('mysql2')->table('mst_editor_database_info')->where("id",$result->id)->update(array("is_first"=>0));
                        DB::disconnect(env('DB_DATABASE'));
                        $user=User::findorfail(1);
                        Auth::login($user);
                        Session::put('auth_token',$token);
                        Session::put('DB_DATABASE',$result->dbname);
                        Session::put('site',$result->paths);
                        return redirect('/info');
                    }
                    $user=User::findorfail(1);
                    Auth::login($user);
                    Session::put('auth_token',$token);
                    Session::put('DB_DATABASE',$result->dbname);
                    Session::put('site',$result->paths);
                    return redirect('/');
                }
            }
            if(Session::has('DB_DATABASE')) {

                Config::set('database.connections.mysql', array(
                    'driver' => 'mysql',
                    'host' => env('DB_HOST'),
                    'port' => env('DB_PORT'),
                    'database' =>Session::get('DB_DATABASE'),

                    'username' => 'username',

                    'password' => 'password,

                    'charset' => 'utf8',

                    'collation' => 'utf8_unicode_ci',

                    'prefix' => '',

                ));

                DB::reconnect('mysql');
            }else{
                Auth::logout();
                Session::flush();
                return redirect('/');
            }

        }
        return $next($request);
    }
}

Register middleware in your App\Http\Kernel.php:

  'web' => [
        \App\Http\Middleware\SetDB::class,
    ],

Using middleware in your routes.php :

Route::group([
    'middleware' => 'web'
], function (){
    
});
2 likes
dmitriydementor's avatar

I created two connections in database config:

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'database_name'),
        'username' => env('DB_USERNAME', 'localhost_admin'),
        'password' => env('DB_PASSWORD', '******'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

    'mysql_admin' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => 'database_name1',
        'username' => env('DB_USERNAME', 'localhost_admin'),
        'password' => env('DB_PASSWORD', '*******'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],

and then I just call this function

DB::setDefaultConnection('mysql_admin');

1 like
ZahidGopang's avatar

@sachinagarwal would you like to share your solution i am also working on multiple database connection we have client wise database.?

Please or to participate in this conversation.