laravel 5.4 dynamic database connection

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 but no luck

please help to sort it out.


ANSWERS:


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(...);

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.



 MORE:


 ? How to initialize a char array as null within a default constructor?
 ? Java Play Framework creating logged in navigation bar - inserting dynamic html in scala template
 ? Dynamic search and filtering in Excel
 ? Dynamic TableView Swift 3 With Beginning Graph
 ? Switch case is not working in Reactjs
 ? Dynamic Polymorphism's weird output
 ? which technologies to use for forms created dynamically?
 ? Winforms - Dynamic Load / Save Settings
 ? Winforms - Dynamic Load / Save Settings
 ? Winforms - Dynamic Load / Save Settings