composer create-project laravel/laravel your-project-name
cd your-project-name
composer require stancl/tenancyphp artisan tenancy:install
php artisan migrateThis creates:
config/tenancy.phproutes/tenant.php- tenant migrations
- provider:
App\Providers\TenancyServiceProvider
Open bootstrap/providers.php and add:
return [
App\Providers\AppServiceProvider::class,
App\Providers\TenancyServiceProvider::class, // ✅ Add this
];Create: app/Models/Tenant.php
namespace App\Models;
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 update your config:
File: config/tenancy.php
'tenant_model' => \App\Models\Tenant::class,Edit config/tenancy.php:
'central_domains' => [
'localhost', // or '127.0.0.1'
],foreach (config('tenancy.central_domains') as $domain) {
Route::domain($domain)->group(function () {
// Central routes here
Route::post('/create-organization', [TenantController::class, 'store']);
});
}In routes/tenant.php:
use Illuminate\Support\Facades\Route;
use Illuminate\Http\Request;
use App\Models\User;
Route::get('/', function () {
dd(User::all());
});✅ Only available on tenant domains, e.g. acme.localhost
mv database/migrations/xxxx_create_users_table.php database/migrations/tenant/Now, each tenant will have its own users table when created.
php artisan tinker
>>> $tenant1 = App\Models\Tenant::create(['id' => 'acme']);
>>> $tenant1->domains()->create(['domain' => 'acme.localhost']);Then seed a user:
>>> $tenant1->run(fn () => \App\Models\User::factory()->create());Visit:
http://localhost→ central apphttp://acme.localhost→ tenant app (you’ll see dumped users)
You extended it to support:
POST
/create-organization
- Creates
tenant - Creates
domain - Adds
employeeto tenant DB
You used:
Tenant::create([...])->run(function () {
Employee::create([...]);
});You made:
// routes/tenant.php
Route::get('/employees', function () {
return Employee::all();
});Optional:
Route::prefix('api')->group(function () {
Route::get('/employees', ...);
});In hosts file:
127.0.0.1 acme.localhost