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 migrations 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.