Zahoor
Zahoor

Reputation: 43

How to configure & run multiple websites with respective databases with single Laravel code instance

I have a scenario that I want to implement in Laravel.

I have already implemented this kind of approach in custom PHP. But this time, I want to shift all websites to a framework (Laravel).

I have multiple domains for different regions implemented (Localization), each domain has its own database and all database tables structure are same only the data is different.

Now I want to use single Laravel code instance with the ability to connect multiple databases with multiple domains and each domain has its own theme files.

Let suppose: I have some domains

 1. abc.com and it has database with name of db_abc with theme/template ABC
 2. xyz.com and it has database with name of db_xyz with theme/template XYZ

When abc.com domain is hit/accessed, I want to connect with DB db_abc and load data in ABC theme/template. Similar when xyz.com is hit/accessed the database connection should be made with db_xyz and data should be loaded into theme/template XYZ files.

Please help me in this regard.

Thank you.

Upvotes: 4

Views: 1415

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163768

First of all, you need to point all domains to a single project.

After that you can catch domains with route group:

Route::group(['domain' => 'abc.com'], function() {
    Route::get('/', 'SomeController@someAction');
});

To use multiple databases you can use connection():

$users = DB::connection('foo')->select(...);

If these are similar websites with similar structure, I'd recomment to keep data in single DB (and maybe even in same tables).

If you want to use same routes for all sites, you could keep DB and views configuration in config file and check for current domain in middleware:

if (strpos(request()->server('HTTP_HOST'), 'abc.com')) {
    session(['site' => 'abc']);
}

And get data from config with:

$currentDb = config('sites.db')[session('site')];
$currentViewsDir = config('sites.views')[session('site')];

Upvotes: 1

Related Questions