php
46 lines · 7 steps
Subdomain multi-tenancy routing in Laravel
A service provider resolves the current tenant from the request host and wires subdomain routes to it.
Explained by
highlit
1<?php
2
3namespace App\Providers;
4
5use App\Models\Tenant;
6use Illuminate\Http\Request;
7use Illuminate\Support\Facades\Route;
8use Illuminate\Support\ServiceProvider;
9use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
10
11class TenantRouteServiceProvider extends ServiceProvider
12{
13 public function boot(): void
14 {
15 $this->app->scoped(Tenant::class, fn () => $this->resolveTenant($this->app['request']));
16
17 Route::bind('tenant', fn () => $this->app->make(Tenant::class));
18
19 $this->routes(function () {
20 Route::domain('{tenant}.'.config('app.central_domain'))
21 ->middleware(['web', 'tenant'])
22 ->group(base_path('routes/tenant.php'));
23
24 Route::middleware('web')->group(base_path('routes/web.php'));
25 });
26 }
27
28 protected function resolveTenant(Request $request): Tenant
29 {
30 $host = $request->getHost();
31 $central = config('app.central_domain');
32
33 if (! str_ends_with($host, '.'.$central)) {
34 throw new NotFoundHttpException('No tenant for the current host.');
35 }
36
37 $slug = substr($host, 0, -\strlen('.'.$central));
38
39 return Tenant::query()
40 ->where('slug', $slug)
41 ->where('is_active', true)
42 ->firstOr(function () use ($slug) {
43 throw new NotFoundHttpException("Unknown tenant [{$slug}].");
44 });
45 }
46}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A scoped container binding resolves once per request, making the current tenant available anywhere via dependency injection.
- 2Route model binding plus subdomain groups let you route by tenant without repeating lookup logic in controllers.
- 3Resolving tenancy from the host and throwing on failure centralizes the rule that unknown hosts must 404.
Related explainers
typescript
import { registerLocaleData } from '@angular/common'; import localeFr from '@angular/common/locales/fr'; import localeFrExtra from '@angular/common/locales/extra/fr'; import localeDe from '@angular/common/locales/de';
Locale-aware bootstrapping in Angular
i18n
localization
dependency-injection
Intermediate
8 steps
php
<?php class NameParser {
Parsing a full name into components in PHP
string-parsing
arrays
normalization
Intermediate
8 steps
typescript
import { Module } from '@nestjs/common'; import { ConfigModule } from '@nestjs/config'; import * as Joi from 'joi';
Validating env config at boot in NestJS
configuration
schema-validation
environment-variables
Intermediate
8 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 steps
java
@Component @Converter public class EncryptedStringConverter implements AttributeConverter<String, String> {
Transparent column encryption in Spring & JPA
encryption
aes-gcm
jpa-converter
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/subdomain-multi-tenancy-routing-in-laravel-explained-php-5408/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.