Create new database on the fly in Laravel 4

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 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(...);


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x