Skip to content
Star16Hire me
01 / StartXP 0%
Dec 25, 2024 · 4 min · by Ahmed Mamdouh

Multi-tenancy with Laravel

#laravel#multi-tenancy#database#tenants#architecture

In a multi-tenant application, one running instance of the software serves several customers, called tenants. In Laravel that usually means one app serving many tenants, and in the setup below each tenant gets its own database.

Multi-tenant Architecture

The approach I'll walk through uses dynamic database connections. You create a database for each tenant, and at runtime the app switches to whichever database belongs to the current tenant.

The steps

  1. Set up a database for each tenant.
  2. Add a connection for each tenant in config/database.php.
  3. Create a Tenant model to represent each tenant.
  4. Use middleware to switch the database connection based on the current tenant.

Set up a database for each tenant

For each tenant you create a new database, using PHPMyAdmin or the MySQL command line. You then give the database user the app connects with the right permissions on that database, which usually means creating a new user per tenant. Finally, you add a connection for the tenant to config/database.php. There's an example config for two tenants further down.

Creating the database in PHPMyAdmin

  1. Open PHPMyAdmin in your browser.
  2. Click the "Databases" tab on the left-hand side.
  3. Enter the database name in the "Create database" field.
  4. Pick the character set and collation from the dropdowns.
  5. Click "Create".

Creating the database from the MySQL command line

  1. Open the MySQL command line interface.
  2. Connect with mysql -u username -p, replacing "username" with your MySQL username.
  3. Enter your password when prompted.
  4. Run CREATE DATABASE database_name, replacing "database_name" with the name you want.

Granting permissions with GRANT

To give a user all privileges on a database:

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost';

That gives the user "username" every privilege on the database "database_name".

You can list specific privileges instead of ALL PRIVILEGES. This one allows only select, insert and update:

GRANT SELECT, INSERT, UPDATE ON database_name.* TO 'username'@'localhost' IDENTIFIED BY 'password';

And to create the user and grant access in one step:

GRANT ALL PRIVILEGES ON database_name.* TO 'username'@'localhost' IDENTIFIED BY 'password';

This creates a user called "username" with the password "password" and gives it all privileges on "database_name".

Add a connection per tenant in config/database.php

Each tenant needs its own entry in the connections array. The exact fields depend on the database driver (MySQL, PostgreSQL, SQLite and so on). For MySQL it looks like this:

'connections' => [
    'tenant1' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'tenant1_db',
        'username' => 'tenant1_user',
        'password' => 'tenant1_password',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
    'tenant2' => [
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'tenant2_db',
        'username' => 'tenant2_user',
        'password' => 'tenant2_password',
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'strict' => true,
        'engine' => null,
    ],
],

Every tenant connection has a unique key, here tenant1 and tenant2, and the values hold the connection details: driver, host, database name, username and password.

Create a Tenant model

A Tenant model gives you one place to store what you know about each tenant: its name, contact details, and which database connection it uses. Generate it with Artisan:

php artisan make:model Tenant

That creates the Tenant class in your app directory.

The attributes come from the columns of the tenants table. For example, a name column for the tenant's name, a db_connection column for its database connection, and a contact_email column for its contact address. The model might look like this:

class Tenant extends Model
{
    protected $fillable = [
        'name',
        'db_connection',
        'contact_email',
    ];
}

Marking name, db_connection and contact_email as fillable lets you mass-assign them through create or update.

Switch the connection in middleware

The middleware looks at the incoming request, works out which tenant it belongs to (for example from a tenant ID passed as a request parameter), and sets the database connection for that tenant before the request goes any further.

Generate it with Artisan:

php artisan make:middleware TenantMiddleware

This puts a TenantMiddleware class in app/Http/Middleware. The switching logic goes in its handle method:

class TenantMiddleware
{
    public function handle($request, Closure $next)
    {
        $tenant = Tenant::find($request->tenant);
 
        if ($tenant) {
            Config::set('database.default', $tenant->db_connection);
        }
 
        return $next($request);
    }
}

It looks up the tenant from the tenant request parameter ($request->tenant) and sets the default database connection to whatever is stored in that tenant's db_connection attribute ($tenant->db_connection).

To use it, register the middleware in the $routeMiddleware array in app/Http/Kernel.php and attach it to the routes that should run against the tenant's database.

Building something like this?

I'm Ahmed Mamdouh, a senior full-stack and AI engineer. I reply within one working day.

More posts