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
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
php
<?php namespace App\Console\Commands;
Releasing stale document locks in Laravel
artisan-command
transactions
row-locking
Intermediate
6 steps
php
<?php namespace App\Broadcasting;
Authorizing presence channels in Laravel
broadcasting
authorization
presence-channels
Intermediate
3 steps
java
@RestController @RequestMapping("/api/products") public class ProductSearchController {
Binding collection query params in Spring
rest-api
query-parameters
dependency-injection
Intermediate
6 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
Intermediate
8 steps
php
<?php namespace App\Http\Controllers;
Broadcasting typing indicators in Laravel
websockets
authorization
presence-channels
Intermediate
9 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.