In my app every user has its own database that created when user registered. Connection and database data (database name, username, password) are saved in a table in default database.
try{
DB::transaction(function() {
$website = new Website();
$website->user_id = Auth::get()->id;
$website->save();
$database_name = 'website_'.$website->id;
DB::statement(DB::raw('CREATE DATABASE ' . $database_name));
$websiteDatabase = new WebsiteDatabase();
$websiteDatabase->website_id = $website->id;
$websiteDatabase->database_name = $database_name;
$websiteDatabase->save();
});
} catch(\Exception $e) {
echo $e->getMessage();
}
Now I want to run some migrations on new user's database after its creation.
Is it possible?
thanks
I think I finally figured out this mess... This solution doesn't need a configuration for each tenant's database and has to be run only once.
Where I have a connection named "tenants" on my database.php, which contains the database name of all of my tenants. I have the default connection set to my tenants database as well. That database is the one responsible for taking care of the migrations table.
With the foreach statement, it goes through the tenant databases and runs the migration on each one.
On your default connection, you should configure a user that has access to all tenant's databases for it to work.
This is tedious to remember which migration corresponds to which database.
For Laravel 5.5 I used this approach:
All migrations can be run automatically without taking care of specifying database manually when running them.
Please note that migrations table is stored inside your default database.
If you place database config on the
database.php
file, this can help you:In your app/config/database.php you have to:
Now that you prepared two database connections in your migration you can do:
This should work. More infos on: http://fideloper.com/laravel-multiple-database-connections
I actually faced the same problem and the answer of Joe did not work in my case, as I have different database connections (so different host, port, user and pass).
Therefore the migration must do a lot of reconnects all the time:
migrations
andclients
And then loop it for each client.
And the class where the magic is stored:
With this solution I can run the exact same migrations on every client, yet the migration is just stored in client_1, my sort of master client.
However, pay attention to the two
DB::disconnect();
. It will screw up the situation without those as then migrations logs are stored in another client's database or such.Ah and by the way, ClientController does nothing special: