How to make a Laravel app multi-tenant in minutes
Published on by Samuel Štancl
In this tutorial, we’ll make your Laravel app multi-tenant using the Tenancy for Laravel package.
It’s a multi-tenancy package that lets you turn any Laravel application multi-tenant without having to rewrite the code. It’s as plug-and-play as tenancy packages get.
Side note: In this tutorial, we’ll go over the most common setup — multi-database tenancy on multiple domains. If you need a different setup, it’s 100% possible. Just see the package’s docs.
How it works
This package is unique in the sense that it doesn’t force you to write your application in a specific way. You can write your app just like you’re used to, and it will make it multi-tenant automatically, in the background. You can even integrate the package into an existing application.
Here’s how it works:
- A request comes in
- The package recognizes the tenant from the request (using domain, subdomain, path, header, query string, etc)
- The package switches the default database connection to the tenant’s connection
- Any database calls, cache calls, queued jobs, etc will automatically be scoped to the current tenant.
Installation
First, we require the package using composer:
composer require stancl/tenancy
Then, we run the tenancy:install
command:
php artisan tenancy:install
This will create a few files: migrations, config file, route file and a service provider.
Let’s run the migrations:
php artisan migrate
Register the service provider in config/app.php
. Make sure it’s on the same position as in the code snippet below:
/* * Application Service Providers... */App\Providers\AppServiceProvider::class,App\Providers\AuthServiceProvider::class,// App\Providers\BroadcastServiceProvider::class,App\Providers\EventServiceProvider::class,App\Providers\RouteServiceProvider::class,App\Providers\TenancyServiceProvider::class, // <-- here
Now we create a custom tenant model. The package is un-opinionated, so to use separate databases and domains, we need to create a slightly customized tenant model. Create a app/Tenant.php
file with this code:
<?php namespace App; use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;use Stancl\Tenancy\Contracts\TenantWithDatabase;use Stancl\Tenancy\Database\Concerns\HasDatabase;use Stancl\Tenancy\Database\Concerns\HasDomains; class Tenant extends BaseTenant implements TenantWithDatabase{ use HasDatabase, HasDomains;}
And now we tell the package to use that model for tenants:
// config/tenancy.php file 'tenant_model' => \App\Tenant::class,
The two parts
The package sees your app as two separate parts:
- the central app — which hosts the landing page, maybe a central dashboard to manage tenants etc
- the tenant app — which is the part that your users (tenants) use. This is likely where most of the business logic will live
Separating the apps
Now that we understand the two parts, let’s separate our application accordingly.
Central app
First, let’s make sure the central app is only accessible on central domains.
Go to app/Providers/RouteServiceProvider.php
and make sure your web
and api
routes are only loaded on the central domains:
protected function mapWebRoutes(){ foreach ($this->centralDomains() as $domain) { Route::middleware('web') ->domain($domain) ->namespace($this->namespace) ->group(base_path('routes/web.php')); }} protected function mapApiRoutes(){ foreach ($this->centralDomains() as $domain) { Route::prefix('api') ->domain($domain) ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); }} protected function centralDomains(): array{ return config('tenancy.central_domains');}
Now go to your config/tenancy.php
file and actually add the central domains.
I’m using Valet, so for me the central domain is saas.test
and tenant domains are for example foo.saas.test
and bar.saas.test
.
So let’s set the central_domains
key:
'central_domains' => [ 'saas.test', // Add the ones that you use. I use this one with Laravel Valet.],
Tenant app
Now, the fun part. This part is almost too simple.
To make some code tenant-aware, all you need to do is:
- move the migrations to the
tenant/
directory - move the routes to the
tenant.php
route file
That’s it.
Having migrations in that specific folder tells the package to run those migrations when a tenant is created. And having routes in that specific route file tells the package to identify tenants on that route.
If you have an existing app, do this with your code. If you’re using a fresh app, follow this example:
Your tenant routes will look like this by default:
Route::middleware([ 'web', InitializeTenancyByDomain::class, PreventAccessFromCentralDomains::class,])->group(function () { Route::get('/', function () { return 'This is your multi-tenant application. The id of the current tenant is ' . tenant('id'); });});
These routes will only be accessible on tenant (non-central) domains — the PreventAccessFromCentralDomains
middleware enforces that.
Let’s make a small change to dump all the users in the database, so that we can actually see multi-tenancy working. Add this to the middleware group:
Route::get('/', function () { dd(\App\User::all()); return 'This is your multi-tenant application. The id of the current tenant is ' . tenant('id');});
And now, the migrations. Simply move migrations related to the tenant app to the database/migrations/tenant
directory.
So, for our example: To have users in tenant databases, let’s move the users table migration to database/migrations/tenant. This will prevent the table from being created in the central database, and it will be instead created in the tenant database when a tenant is created.
Trying it out
And now let’s create some tenants.
We don’t yet have a landing page where tenants can sign up, but we can create them in tinker!
So let’s open php artisan tinker
and create some tenants. Tenants are really just models, so you create them like any other Eloquent models.
Note that we’re using domain identification here. So make sure the domains you use will point to your app. I’m using Valet, so I’m using *.saas.test
for tenants. If you use php artisan serve
, you can use foo.localhost
, for example.
>> $tenant1 = Tenant::create(['id' => 'foo']); >> $tenant1->domains()->create(['domain' => 'foo.saas.test']);>>> >> $tenant2 = Tenant::create(['id' => 'bar']); >> $tenant2->domains()->create(['domain' => 'bar.saas.test']);
And now we’ll create a user inside of each tenant’s database:
App\Tenant::all()->runForEach(function () { factory(App\User::class)->create();});
And that’s it — we have a multi-tenant app!
If you visit foo.saas.test
(or your environment’s equivalent), you will see a dump of users.
If you visit bar.saas.test
, you will see a dump of different users. The databases are 100% separated, and the code we use — App\User::all()
— does not need to know about tenancy at all! It all happens automatically in the background. You just write your app like you’re used to, without having to think of any scoping yourself, and it all just works.
Now, of course, you will have a more complex app inside the tenant application. A SaaS that simply dumps users wouldn’t probably be of much use. So that’s your job — write the business logic that will be used by your tenants. The package will take care of the rest.
The Tenancy for Laravel project’s help doesn’t end there though. The package will do all the heavy lifting related to multi-tenancy for you. But if you’re building a SaaS, you will still need to write billing logic, an onboarding flow, and similar standard things yourself. If you’re interested, the project also offers a premium product: the multi-tenant SaaS boilerplate. It’s meant to save you time by giving you the SaaS features you’d normally have to write yourself. All packed in a ready to be deployed multi-tenant app. You may read more about it here.
Final note: This tutorial is meant to show you how simple it is to create a multi-tenant app. For your reading comfort, it’s kept short. For more details, read the package’s quickstart tutorial or the documentation.
Good luck with your SaaS!
I'm a freelance Laravel developer and the creator of http://tenancyforlaravel.com.