baao
baao

Reputation: 73241

laravel 5 set Database with parameters from Session

I'm building an app where different users are accessing different databases.

In laravel 4, it was as easy as defining the database connection like so:

    'usertable' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST'),
        'database'  => Session::get('table'), << works for laravel 4
        'username'  => env('DB_USERNAME'),
        'password'  => env('DB_PASSWORD'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

However, laravel 5 throws an error:

Class 'Session' not found in ...

I have tried to import Session in multiple ways and with every namespace I have found which could be Session's namespace, but nothing works at all and the error persists.

It seems like laravel5 would load the database class with all the possible connections before the Session class is autoloaded.

Is there another way to create database connections for different users? Or can someone suggest another way to do so?

Upvotes: 0

Views: 1503

Answers (1)

Noman Ur Rehman
Noman Ur Rehman

Reputation: 6957

Laravel provides a facade to access configuration at runtime.

Config::set('database.default', 'sqlite');

From the Laravel docs:

"Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests."

I think this is a more viable solution. You can call this function and set the database from session for each request.

Or better, use a middleware and just mount it to handle the database setting before each request.

Upvotes: 2

Related Questions