1

I am working on a multi tenant multi DB application and I am working on registering tenants right now. So I am trying to register tenants right now. In the process of registering a tenant, a new record is being created in the main DB, a new DB is created for the tenant too.

Now I wish to migrate the new tenant DB with the tenant migration but sadly I don't know how to change the DB connection dynamically and migrate all the tables and setup an admin account for him.

<?php

namespace App\Http\Controllers\Auth;

use App\Tenant;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;

use Illuminate\Http\Request;

class AuthController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Registration & Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles the registration of new users, as well as the
    | authentication of existing users. By default, this controller uses
    | a simple trait to add these behaviors. Why don't you explore it?
    |
    */

    use AuthenticatesAndRegistersUsers, ThrottlesLogins;

    /**
     * Create a new authentication controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'getLogout']);
    }

    protected $redirectTo = '/auth/login';

    /**
     * Get a validator for an incoming registration request.
     *
     * @param  array  $data
     * @return \Illuminate\Contracts\Validation\Validator
     */
    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|max:255',
            'username' => 'required|max:255|unique:tenants',
            'email' => 'required|email|max:255',
            'password' => 'required|confirmed|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function createTenant(array $data)
    {
        return Tenant::create([
            'name' => $data['name'],
            'username' => $data['username'],
        ]);
    }

    protected function createDbForNewTenant($username)
    {
        \DB::statement('CREATE DATABASE ' . $username);
    }

    public function getRegister()
    {
        return view('auth.register');
    }

    public function getLogin()
    {
        return view('auth.login');
    }

    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }

        $this->createTenant($request->all());
        $this->createDbForNewTenant($request->username);

        \Config::set('database.connections.archive.database', $request->username);

        \Artisan::call('migrate', [
            '--path' => 'database/migrations/archive'
        ]);

        return redirect($this->redirectPath());
    }
}

So if you look at the postRegister, I am able to do validations okay, I am able to create a new record okay and create the DB too. But now I need to change my connection to that DB and run the migration command. I am using the Config to set the database key but I still don't see the migrations running.

What am I doing wrong?

EDIT

'connections' => [

    'archive' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

    'tenant' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

],
Rohan
  • 13,308
  • 21
  • 81
  • 154
  • You can dynamically access multiple connections within Laravels database config file. Here is a great article that shows how to do it. http://fideloper.com/laravel-multiple-database-connections – Jordan Bardsley Oct 05 '15 at 01:10
  • Yes but what is the suitable one out of this for my problem. I have tried `Eloquent::setConnection()` and that gives me an error that I cannot call it statically. I have tried `$this->setConnection()` but that also gives me an error because I am in the auth controller with is not an instance of eloquent. – Rohan Oct 05 '15 at 07:16
  • Can you show me how your database config file looks (obviously without the real credentials). You would want to do something of this manner. `$users = DB::connection('mysql2')->select(...);` – Jordan Bardsley Oct 06 '15 at 22:02
  • I just edited my question to reflect the database config file. Look into it whenever you find time. Thank you. :) – Rohan Oct 09 '15 at 06:34

0 Answers0