iftekhs's avatar
Level 13

Multitenancy - Single codebase Multiple database

Hi! I'm actually planning to create a Saas product that will have a single codebase and multiple databases and I want to know how to correctly set up this set by step. So can you guys give me some advice on this or maybe provide me with a resource where I can learn the proper way to build a single codebase and multiple database architecture Site?

Thank you so much!

0 likes
3 replies
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

To set up a multitenancy system with a single codebase and multiple databases, you can follow these steps:

  1. Create a separate database for each tenant. This can be done manually or programmatically, depending on your requirements.

  2. Configure your application to dynamically switch between databases based on the current tenant. This can be done using a middleware or a service provider.

  3. Use a unique identifier to identify each tenant. This can be a subdomain, a domain, or a custom identifier.

  4. Store the tenant identifier in a session or a cookie, so that it can be accessed throughout the application.

  5. Use a database connection manager to manage the database connections for each tenant. This can be done using a package like Laravel's Tenancy or a custom solution.

  6. Use a database migration manager to manage the database migrations for each tenant. This can be done using a package like Laravel's Tenancy or a custom solution.

  7. Use a database seeder manager to manage the database seeders for each tenant. This can be done using a package like Laravel's Tenancy or a custom solution.

Here's an example of how to switch between databases based on the current tenant using a middleware in Laravel:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class TenantMiddleware
{
    public function handle($request, Closure $next)
    {
        $tenant = $request->getHost(); // or any other identifier

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

        DB::reconnect('tenant');

        return $next($request);
    }
}

You can then register this middleware in your Kernel.php file:

protected $middlewareGroups = [
    'web' => [
        // ...
        \App\Http\Middleware\TenantMiddleware::class,
    ],
];

This is just a basic example, and you may need to customize it based on your requirements.

iftekhs's avatar
Level 13

@martinbean Yes that is indeed a hassle but there is "Laravel Tenancy" which implements these kind of things so is it really not a good idea to implement it?

Please or to participate in this conversation.