Laravel 5 — Simple Subdomain for Multi-Tenant Application

Photo by rawpixel on Unsplash

Introduction

Route::domain('{account}.myapp.com')->group(function () {
Route::get('user/{id}', function ($account, $id) {
//
});
});
route('routeName', ['account' => 'account-one']);

1. Get Tenant from Subdomain

Setup

Middleware

php artisan make:middleware CheckTenant

Code breakdown

list($subdomain) = explode('.', $request->getHost(), 2);
$tenant = Tenant::whereSlug($subdomain)->first() ?: abort(404);
$request->session()->put('tenant', $tenant);

Register Middleware

protected $middlewareGroups = [
'web' => [
...,
\App\Http\Middleware\CheckTenant::class,
],
...
];

Result

2. (Additional) Tenant’s User

Setup

php artisan make:auth

Middleware

Code breakdown

if ($request->user() == null) {
return $next($request);
}
$has_access = $request->user()->tenant == $tenant;
if (!$has_access) {
Auth::logout();
return redirect('/login')->with('no_access', true);
} else {
$request->session()->put('has_access', true);
}
$has_access = $request->session()->get('has_access');
if ($has_access) {
return $next($request);
}

Login View

@if (session('no_access'))
<div class="alert alert-danger">
You have no access to this Tenant.
</div>
@endif

Result

To Study Further

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store