Create new database on the fly in Laravel 4

早过忘川 提交于 2019-12-13 03:38:26

问题


I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website.

Whats the best solution?

thanks.


回答1:


This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods:

DB::statement(DB::raw('CREATE DATABASE <name>'));

To do that you can use a secondary connection:

<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
        ),

        'store' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
        ),
    ),
);

Then you can, during application bootstrap, change the database of the secondary connection:

DB::connection('store')->setDatabaseName($store);

or

Config::set('database.connections.store', $store);

And use the secondary connection in your queries:

$user = User::on('store')->find(1);

or

DB::connection('store')->select(...);


来源:https://stackoverflow.com/questions/25821291/create-new-database-on-the-fly-in-laravel-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!