Search code examples
laravellaravel-4database-migrationmulti-tenant

Laravel: Run migrations on another database


In my app, every user has its own database that created when the user registered. Connection and database data (database name, username, password) are saved in a table in the 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?


Solution

  • If you mean using different database connection, it exists in the docs:

    Schema::connection('foo')->create('users', function (Blueprint $table) {
        $table->bigIncrements('id');
    });