How to Build a Multi-Tenant SaaS Application in Laravel

Laravel Multi-Tenant SaaS Application Tutorial

A **Multi-Tenant SaaS application** allows multiple businesses or clients to use a single Laravel application while maintaining data isolation. In this tutorial, we will use **Laravel and the tenancy package** to set up a multi-tenant architecture.

Step 1: Install Laravel

First, create a new Laravel project:

composer create-project --prefer-dist laravel/laravel MultiTenantSaaS

Step 2: Install Laravel Tenancy Package

We will use the **tenancy/tenancy** package to manage tenants.

composer require stancl/tenancy

Step 3: Publish the Configuration Files

php artisan tenancy:install

This will generate the necessary migrations and config files.

Step 4: Configure the Tenant Model

Edit `app/Models/Tenant.php`:

namespace App\Models;
use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    protected $fillable = ['id', 'name'];
}

Step 5: Configure Database Connections

Modify `config/database.php`:

'connections' => [
    'tenant' => [
        'driver' => 'mysql',
        'host' => env('TENANT_DB_HOST', '127.0.0.1'),
        'database' => null,
        'username' => env('TENANT_DB_USERNAME', 'root'),
        'password' => env('TENANT_DB_PASSWORD', ''),
    ],
],

Step 6: Create Tenant Registration

Generate a Tenant Controller:

php artisan make:controller TenantController

Modify `TenantController.php`:

namespace App\Http\Controllers;
use App\Models\Tenant;
use Illuminate\Http\Request;

class TenantController extends Controller {
    public function create(Request $request) {
        $tenant = Tenant::create(['id' => $request->subdomain, 'name' => $request->name]);
        return response()->json(['message' => 'Tenant created successfully', 'tenant' => $tenant]);
    }
}

Step 7: Setup Multi-Tenant Middleware

php artisan make:middleware TenantMiddleware

Modify `TenantMiddleware.php`:

namespace App\Http\Middleware;
use Closure;
use Stancl\Tenancy\Tenancy;

class TenantMiddleware {
    public function handle($request, Closure $next) {
        tenancy()->initialize($request->route('tenant'));
        return $next($request);
    }
}

Step 8: Define Routes

use App\Http\Controllers\TenantController;
Route::post('/tenants', [TenantController::class, 'create']);

Step 9: Run Migrations

php artisan migrate

Step 10: Test Multi-Tenancy

Now, register a tenant and test the setup.

Conclusion

You have successfully built a **multi-tenant SaaS application in Laravel**. 🚀 Now, multiple businesses can use your platform with **data isolation**.

0 Comments