HouZer
HouZer

Reputation: 1

Change database connection when using Laravel Auth

In a multi-tenant Laravel app, each tenant has its own database connection. So after the user has selected his database, I want to authenticate the user using Auth::loginUsingId. Still, no matter what I do, I cannot change the Users Model's connection to another default.

If I set the connection in the model, it does connect to the specific database, but I want this to be done dynamically.

Is there a way to specify the connection dynamically that Laravel's auth should use for the authentication?

Upvotes: 0

Views: 1222

Answers (2)

user9453520
user9453520

Reputation:

You could define another connection in your config/database.php file like this:

return array(
    'connections' => array(
        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

        'second_db_connection' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
    )

And change the User model to be like this:

class User extends Model {

    protected $connection = 'second_db_connection';
    
}

Upvotes: 1

Amir
Amir

Reputation: 721

Before authenticating the user, change the database connection temporarily for the current request only using Conifg::set

$db = "database_name";
Config::set("database.connections.mysql.database", $db);

Upvotes: 0

Related Questions