如何在Laravel中动态更改数据库连接?

时间:2015-10-04 18:31:29

标签: php mysql laravel laravel-5 multi-tenant

我正在开发一个多租户多数据库应用程序,我正在努力注册租户。所以我现在正试图注册租户。在注册租户的过程中,在主DB中创建了一条新记录,也为租户创建了一个新的数据库。

现在我希望通过租户迁移迁移新租户数据库,但遗憾的是我不知道如何动态更改数据库连接并迁移所有表并为他设置管理员帐户。

<?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());
    }
}

因此,如果您查看postRegister,我可以进行验证,我可以创建新记录,也可以创建数据库。但是现在我需要更改与该数据库的连接并运行迁移命令。我使用Config设置数据库密钥,但我仍然没有看到正在运行的迁移。

我做错了什么?

修改

'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,
    ],

],

1 个答案:

答案 0 :(得分:0)

您可以在Laravels数据库配置文件中动态访问多个连接。

这是一篇很棒的文章,展示了如何做到这一点。

http://fideloper.com/laravel-multiple-database-connections