How to use Multi Tenant with Multi Databases Into Any Laravel Application ?

Laravel
June 02, 20221 minuteuserVishal Ribdiya
How to use Multi Tenant with Multi Databases Into Any Laravel Application ?

People are quite afraid :), including me :) when it’s about the developing system that works with multi-tenant / multi-database.

In this tutorial, we will implement a multi-tenant system that will create a separate database when the new tenant will create.

Install Package

composer require stancl/tenancy

Then run the following command :

php artisan tenancy:install

Then add the service provider TenancyServiceProvider to your config/app.php file:

/*
 * 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

Setup Tenant Model

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;
}

Then, configure the package to use this model in config/tenancy.php:

'tenant_model' => \App\Tenant::class,

Create Migrations For tenant

Create one migration and move that migration file to migrations/tenant. So when we are going to create new tenant this migarations files will run for that new tenant.

You can do the same for seeders. if you want to change the seeder file then you can change it from the config/tenancy.php

Create Actual Tenant

$tenant = Tenant::create([
    'id' => time(),
]);

Result

Now when we run above code it will create new tenant and also create new database with related prefix and given id value.

So it will create following things :

  • New Tenant will be created in main database
  • New tenant database will be created
  • New migrations and seeders will be executed into new tenant database.

Hope that will helps a lot.