How to Build a Multi-Tenant Application in Laravel 12 with stancl/tenancy

Quickly turn Laravel into a multi-tenant SaaS using stancl/tenancy. Isolate tenant data with separate databases, configure domains, and automate migrations. Follow simple steps: install, set up routes, create tenants, and test. Perfect for scalable projects! #Laravel #SaaS 🚀

How to Build a Multi-Tenant Application in Laravel 12 with stancl/tenancy Image

Multi-tenancy is an essential feature for SaaS applications, allowing you to serve multiple customers from a single application instance while keeping their data separate. In this guide, we'll walk through implementing multi-tenancy in Laravel 12 using the popular stancl/tenancy package.

Are you building a SaaS application or need to manage multiple clients with isolated data in a single Laravel project? In this comprehensive tutorial, you'll learn how to implement multi-tenancy in Laravel 12 using the powerful and developer-friendly stancl/tenancy package. This guide walks you through setting up subdomain-based tenants, handling tenant-specific databases, and configuring your Laravel app for a true multi-tenant architecture. Whether you're developing a Laravel SaaS application, CRM, or client portal, this step-by-step approach will help you get started with scalable, secure, and efficient tenant management.

Prerequisites

Before we begin, ensure you have:

  • A fresh Laravel 12 installation
  • Basic knowledge of Laravel and databases
  • Understanding of DNS, wildcard domains, and server configuration
  • PHP and Composer installed on your system

Step 1: Install the Package

First, install the tenancy package via Composer:

composer require stancl/tenancy

Step 2: Create Tenancy Default Files

Run the installation command to set up the basic tenancy files:

php artisan tenancy:install

This command creates:

  • Necessary migrations
  • Configuration file (config/tenancy.php)
  • Tenant route file (routes/tenant.php)
  • A service provider (app/Providers/TenancyServiceProvider.php)

Step 3: Run the Migrations

Migrate the database to create tables needed for tenancy:

php artisan migrate

Step 4: Register the Service Provider

Add the TenancyServiceProvider to bootstrap/providers.php:

return [
    App\Providers\AppServiceProvider::class,
    App\Providers\TenancyServiceProvider::class, // <-- Add this line
];

Step 5: Create a Custom Tenant Model

Generate a Tenant model:

php artisan make:model Tenant

Replace the contents with:

<?php

namespace App\Models;

use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Database\Concerns\HasDatabase;
use Stancl\Tenancy\Database\Concerns\HasDomains;

class Tenant extends BaseTenant implements TenantWithDatabase
{
    use HasDatabase, HasDomains;
}

Update config/tenancy.php to use your custom model:

'tenant_model' => \App\Models\Tenant::class,

Step 6: Configure Central Domains

In your routes/web.php, wrap your central domain routes:

foreach (config('tenancy.central_domains') as $domain) {
    Route::domain($domain)->group(function () {
        // Your central domain routes here
    });
}

Add your central domains to config/tenancy.php:

'central_domains' => [
    'saas.test', // Replace with your actual domain
],

Step 7: Set Up Tenant Routes

Your tenant routes (in routes/tenant.php) will look like:

Route::middleware([
    'web',
    InitializeTenancyByDomain::class,
    PreventAccessFromCentralDomains::class,
])->group(function () {
    Route::get('/', function () {
        dd(\App\Models\User::all());
        return 'This is your multi-tenant application. The id of the current tenant is ' . tenant('id');
    });
});

Step 8: Create Tenants for Testing

Let's create a test tenant using tinker:

php artisan tinker
$tenant1 = App\Models\Tenant::create(['id' => 'foo']);
$tenant1->domains()->create(['domain' => 'foo.localhost']);.

Step 9: Handle Tenant Migrations

Create tenant-specific migrations in database/migrations/tenant directory. Then run:

php artisan tenants:migrate

This will create databases for each tenant (tenant ID) and run migrations in them.

Step 10: Configure Local Domain

Add your tenant domain to your hosts file:

127.0.0.1 foo.localhost

Step 11: Serve the Application

Start the development server:

php artisan serve

Now visit your tenant domain (e.g., foo.localhost:8000) to see multi-tenancy in action!

Conclusion

You've now successfully set up multi-tenancy in Laravel 12 using the stancl/tenancy package. This implementation provides:

  • Separate databases for each tenant
  • Domain-based tenant identification
  • Automatic tenant database creation
  • Isolation of tenant data

From here, you can expand the functionality by:

  • Creating tenant registration flows
  • Adding tenant-specific configurations
  • Implementing payment systems for tenant subscriptions
  • Building tenant management interfaces
  • Set specific database name and credential for tenant (individual)

The stancl/tenancy package offers many more features like filesystem isolation, cache isolation, and job queuing per tenant. 

Explore the official documentation to unlock the full potential of multi-tenancy in your Laravel application.

Happy Coding! 😊

Do you Like?