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

Walkthrough

Space play step click any line
Three takeaways
  1. 1A scoped container binding resolves once per request, making the current tenant available anywhere via dependency injection.
  2. 2Route model binding plus subdomain groups let you route by tenant without repeating lookup logic in controllers.
  3. 3Resolving tenancy from the host and throwing on failure centralizes the rule that unknown hosts must 404.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Subdomain multi-tenancy routing in Laravel — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code