0

I am building the admission portal in laravel,

I have super admin database which has a schools table with 100 rows, schools table structure 1.id 2.school_name 3.database details

I want to connect to the school database with its database details by its id.

technically 1.I will pass the school id from url 2.it will select that row from school table 3.after selecting the database details of particular school 4.will connect to the school database for further use.

I went through https://laracasts.com/discuss/channels/tips/set-up-dynamic-database-connection-globally http://fideloper.com/laravel-multiple-database-connections but no luck

please help to sort it out.

Gokul.T
  • 75
  • 3
  • 9

2 Answers2

2

Actually you dont want multiple connections, but rather change existing connection.

public function setSchoolConnection($id) {
    $school = School::find($id);

    if ( $school ) {
        config(['database.mysql' => [
            'database' => $school->database,
            'username' => $school->username,
            'password' => $school->password
         ]]);
    }
}

Now the default connection has been changed. I think.

If you don't want to change existing connection, just create a new connectio

config(['database.school' => [
    'driver'   => 'mysql',
    'database' => $school->database,
    'username' => $school->username,
    'password' => $school->password
]]);

and use it like this

$users = DB::connection('school')->select(...);
EddyTheDove
  • 12,979
  • 2
  • 37
  • 45
  • but if I go by these way I need to make the connection for each route request means needs to write the same code in each function of every controller and I dont want to do that – Gokul.T Mar 23 '17 at 12:34
  • 1
    If you don't go this way, then you need to manually add the routes to the config. You could add this into a middleware. So for each request, the school will use the right database. Right now, it's really entirely up to you. – EddyTheDove Mar 23 '17 at 12:37
0

Have you tried setting the connection in the School model? Laravel will take care of the rest, even if you have relations with different connection.

In your School model, I will override the constructor like so:

public function __construct(array $attributes = [])
{
    $this->setConnection(env('DB_SCHOOL_CONNECTION'));

    parent::__construct($attributes);
}

The one thing to be careful of is if you have a relation with a different connection, using whereHas or has in your query/builder wont work. as laravel will not be able to set the connection in the query generated.

Ayo Akinyemi
  • 792
  • 4
  • 7