How to use single codebase and mutiple databases for client

We have multiple client portal each one has a unique url like

  • .. ..

We will be routing all these url's to /var/www/html/laravelapp/public (laravelapp is our codebase which we use for all the clients).

Now my question is how do we use get client portal identifier(ClientPotalXXX) in laravelapp and make it accessible globally to load the client specific settings like database connection(Each client has a different database),url's etc..

Possible solution to get the client identifier from url is by using super global variable $_SERVER but where to write all that logic and how do I make it accessible globally in my laravelapp?

Tobias van Beek replied 1 year ago

You could use a Middleware to change the database config depending the client portal identifier. Depending if you have all the configurations in your database file or that it is flexibel you need to decide how you want to validate it.

HouseOfCoder replied 1 year ago

Do you mean I should be writing the logic of fetching client identifier from url in Middleware and make it accessible globally?

Tobias van Beek replied 1 year ago

A middleware can be for all the routes. And you can change the default connection on the fly (only for that request)

$clientIdentifier = 'client1234';
config(['database.default' => $clientIdentifier]);

HouseOfCoder replied 1 year ago

My Web.php file is as below..

   Application URL : 
   Where ClientXXX  is dynamic 

Route::prefix('/{ClientPortal}')->group(function () {
    Route::get('/user/edit/{id}', '[email protected]');

I've created Middleware with below code written in it..

public function handle($request, Closure $next)
    $database_name = strtolower($request->ClientPortal).'_db';
    return $next($request);

And it's working fine but previously I used to access $id in edit function as a parameter directly public function edit($id)

but now $id return the value of {ClientPortal} every time but If i access $id like

public function edit(Request $request){
    $id = $request->id;

It's working fine so I'm not sure if this happened because I'm using dynamic prefix for grouping all the routes? And now for in every route() function which I have used in blade files for url generation I have to pass the second parameter ie. value of **ClientPortal **

{{ route('register',['ClientPortal'=>config('app_settings.client')]) }}

is this write implementation?

HouseOfCoder replied 1 year ago

I've asked the same question on stackoverflow:

Sign in to participate in this thread!

We'd like to thank these amazing companies for supporting us