简体   繁体   中英

Is it possible to use Session::get() method in database.php file?

I am Abdullah. I want to use multiple database connection in laravel 5.6. But i want change the database dynamically. best way for me the using Session::get() method in config/database.php.

'connections' => [

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

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

],

I want to change the changeable database by using Session::get('db') method. is it possible or any other way?

I don't think that is possible because when you change any configuration in your config file and use php artisan to serve you application. You have to stop the running serve and restart It for laravel to take in consideration new configuration. Laravel doesn't hot reload configuration.

My advice is to define many connection inside the database.php file as you need and when you whan to switch to another connection you can specify it by providing the name of the given connection like this

$users = DB::connection('connection_name')
    ->table('users')
    ->where('name', 'John')->first();

You can switch connection has you need inside Controller or somewhere else

If you want to change connection on specific Model you can perform it this way

$user = new user();
$user->setConnection('connection_name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM