Implementing multitenancy in Laravel allows you to serve multiple clients (tenants) from a single application instance. There are several approaches to achieve this, but two of the most common methods are:
- Single Database with Tenant ID: All tenants share the same database, and each record has a
tenant_id
to differentiate data. - Multiple Databases: Each tenant has their own database.
Method 1: Single Database with Tenant ID
Step 1: Create the Tenant Model and Migration
- Create the Tenant Model:
1 |
php artisan make:model Tenant -m |
- Define the Migration:
In the migration file, create a tenants
table:
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('tenants', function (Blueprint $table) { $table->id(); $table->string('name')->unique(); $table->string('database')->unique(); // If using multiple databases $table->timestamps(); }); } |
Step 2: Update Your Models
Add a tenant_id
field to your other models (e.g., Post
):
- Create a Migration:
1 |
php artisan make:migration add_tenant_id_to_posts_table --table=posts |
- Update the Migration:
1 2 3 4 5 6 |
public function up() { Schema::table('posts', function (Blueprint $table) { $table->foreignId('tenant_id')->constrained()->onDelete('cascade'); }); } |
Step 3: Define Relationships
In the Tenant
model, define the relationship:
1 2 3 4 5 6 7 8 9 10 11 |
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Tenant extends Model { public function posts() { return $this->hasMany(Post::class); } } |
In the Post
model, define the inverse relationship:
1 2 3 4 5 6 7 8 9 10 11 |
namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { public function tenant() { return $this->belongsTo(Tenant::class); } } |
Step 4: Middleware for Tenant Identification
Create middleware to identify the tenant based on the request. For example, you can use subdomains or request headers.
- Create Middleware:
1 |
php artisan make:middleware TenantMiddleware |
- Update the Middleware:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
namespace App\Http\Middleware; use Closure; use App\Models\Tenant; class TenantMiddleware { public function handle($request, Closure $next) { // Example: Get tenant from subdomain $subdomain = explode('.', $request->getHost())[0]; $tenant = Tenant::where('name', $subdomain)->firstOrFail(); // Set the tenant in the application (you might want to use a service provider for this) app()->instance('currentTenant', $tenant); return $next($request); } } |
Step 5: Register the Middleware
Register the middleware in app/Http/Kernel.php
:
1 2 3 |
protected $routeMiddleware = [ 'tenant' => \App\Http\Middleware\TenantMiddleware::class, ]; |
Step 6: Use Tenant Data in Queries
In your controllers, use the tenant data:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
namespace App\Http\Controllers; use App\Models\Post; class PostController extends Controller { public function index() { $tenant = app('currentTenant'); $posts = Post::where('tenant_id', $tenant->id)->get(); return view('posts.index', compact('posts')); } } |
Method 2: Multiple Databases
If each tenant has a separate database, you can switch the database connection dynamically.
Step 1: Create Tenant Databases
In your tenants
table, store the database names.
Step 2: Configure Database Connection
In your TenantMiddleware
, switch the database connection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
use Illuminate\Support\Facades\DB; class TenantMiddleware { public function handle($request, Closure $next) { // Get the tenant based on subdomain $tenant = Tenant::where('name', $subdomain)->firstOrFail(); // Set the database connection dynamically config(['database.connections.tenant.database' => $tenant->database]); DB::purge('tenant'); return $next($request); } } |
Step 3: Update Database Config
In config/database.php
, define a tenant
connection:
1 2 3 4 5 6 7 8 9 10 11 12 |
'tenant' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'database' => '', 'username' => env('DB_USERNAME', 'forge'), 'password' => env('DB_PASSWORD', ''), 'charset' => 'utf8mb4', 'collation' => 'utf8mb4_unicode_ci', 'prefix' => '', 'strict' => true, 'engine' => null, ], |
Conclusion
With these methods, you can implement multitenancy in Laravel either by using a single database with tenant IDs or by utilizing multiple databases. Choose the approach that best fits your application’s requirements. Make sure to test thoroughly to ensure that data isolation and integrity are maintained across tenants.