Backend Development Laravel Subjective
Sep 30, 2025

Explain Multi-tenancy implementation in Laravel with code examples.

Detailed Explanation
Multi-tenancy allows serving multiple tenants from single application: **Single Database Approach:**
// Migration
Schema::create("tenants", function (Blueprint $table) {
    $table->id();
    $table->string("name");
    $table->string("domain");
    $table->timestamps();
});

// Add tenant_id to all tables
$table->foreignId("tenant_id")->constrained();
**Tenant Model:**
class Tenant extends Model {
    protected $fillable = ["name", "domain"];
    
    public function users() {
        return $this->hasMany(User::class);
    }
}
**Middleware for Tenant Resolution:**
class ResolveTenant {
    public function handle($request, Closure $next) {
        $domain = $request->getHost();
        $tenant = Tenant::where("domain", $domain)->first();
        
        if (!$tenant) {
            abort(404);
        }
        
        app()->instance("tenant", $tenant);
        return $next($request);
    }
}
**Global Scope for Models:**
class TenantScope implements Scope {
    public function apply(Builder $builder, Model $model) {
        if (app()->has("tenant")) {
            $builder->where("tenant_id", app("tenant")->id);
        }
    }
}
Discussion (0)

No comments yet. Be the first to share your thoughts!

Share Your Thoughts
Feedback