w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Laravel - Multi-tenancy - One database multiple tables

You can set tenant name as a prefix in your database file:

Config::set('database.connections.mysql.prefix',$tenantName);
// assuming 'mysql' is the default database connection name

I recommend to put it inside a filter

// routes.php
Route::group(array('before'=>'setTablePrefix'), function($noob)
{
    Route::resource('customers', 'CustomersController');
    Route::controller('sales', 'SalesController');
});
Route::get('/login',array('as' => 'login', 'uses' =>
'UserController@getLogin'));


// filters.php
Route::filter('setTablePrefix', function($route, $request) 
{
    if (!Session::has('prefixTable'))
        App::abort(404);
   
Config::set('database.connections.mysql.prefix',Session::get('prefixTable'));
});

To get data from all tables, you probably need two queries (or one if you use Session)

$tenants =
DB::table('tenants')->lists('name'); // you can set it in Session
if($tenants){
    $allCustomers = DB::table($tenants[0].'.customers');
    for ($i = 1; $i < count($tenants); $i++) { 
        $allCustomers->unionall(DB::table($tenants[$i].'.customers'));
    }
    var_dump($allCustomers->get()); 
}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.