Courses

Laravel 11 Multi-Tenancy: All You Need To Know

"Wildcard" Subdomain for Every Tenant

Summary of this lesson:
- Adding unique subdomain field to tenants table
- Setting up wildcard subdomains with SESSION_DOMAIN
- Handling subdomain redirects during tenant switching
- Ensuring security through database tenant validation

Now, let's talk about subdomains. This is a typical way to structure multi-tenancy projects, and how to separate tenants so every tenant would have a "personal space". Fake, but personal space.

What do I mean by fake? Why is it fake?

Because subdomains can't act as a security filter, it wouldn't be secure enough. For example, we have a tenancy.test domain. And for every tenant/company/team, we create a subdomain like povilas.tenancy.test.

If I take just the URL and filter the data by that URL, anyone could fake my URL without even being logged in. Another way would be to log into another tenant, replace their URL, and land onto my workspace, which is a security issue.

So, in this lesson, we will create subdomains. I will show you how it works, but you need to understand correctly that it is more like the cherry on top, like part of the design of your application, but not the secure authentication of the tenant.

Let's implement these features:

  1. Register the subdomain during the registration and then redirect to the correct subdomain.
  2. When switching between the tenants, redirect them to their subdomain.

Registering the Subdomain

In the registration form, let's add the input for the subdomain.

resources/views/auth/register.blade.php:

// ...
 
<!-- Email Address -->
<div class="mt-4">
<x-input-label for="email" :value="__('Email')" />
<x-text-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
 
<!-- Subdomain -->
<div class="mt-4">
<x-input-label for="subdomain" :value="__('Subdomain')" />
<x-text-input id="subdomain" class="block mt-1 mr-2 w-full" type="text" name="subdomain" :value="old('subdomain')" required />
<x-input-error :messages="$errors->get('subdomain')" class="mt-2" />
</div>
 
<!-- Password -->
 
// ...
</x-guest-layout>

Next, create a subdomain column in...

The full lesson is only for Premium Members.
Want to access all 22 lessons of this course? (88 min read)

You also get:

  • 69 courses (majority in latest Laravel 11)
  • Premium tutorials
  • Access to repositories
  • Private Discord