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:

  1. A request comes in
  2. The package recognizes the tenant from the request (using domain, subdomain, path, header, query string, etc)
  3. The package switches the default database connection to the tenant’s connection
  4. 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,

#laravel

How to Make a Laravel app multi-tenant in minutes
57.70 GEEK