PHP code example of rylxes / laravel-multitenancy

1. Go to this page and download the library: Download rylxes/laravel-multitenancy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

rylxes / laravel-multitenancy example snippets


Schema::table('projects', function (Blueprint $table) {
    $table->foreignId('tenant_id')->constrained()->index();
});

use Illuminate\Database\Eloquent\Model;
use Rylxes\Multitenancy\Concerns\BelongsToTenant;

class Project extends Model
{
    use BelongsToTenant;
}

// routes/web.php or bootstrap/app.php
Route::middleware('tenancy')->group(function () {
    Route::resource('projects', ProjectController::class);
});

'tenant_finder' => \Rylxes\Multitenancy\Finders\DomainTenantFinder::class,

use Rylxes\Multitenancy\Concerns\BelongsToTenant;

class Invoice extends Model
{
    use BelongsToTenant;
}

// Automatically adds WHERE tenant_id = ? to all queries
$invoices = Invoice::all(); // Only current tenant's invoices

// tenant_id auto-filled on create
$invoice = Invoice::create(['amount' => 100]); // tenant_id set automatically

// Without any tenant context active:
Invoice::all(); // Throws NoCurrentTenantException

// Get all invoices across all tenants (admin use)
$allInvoices = Invoice::withoutTenantScope()->get();

// config/multitenancy.php
'switch_tenant_tasks' => [
    PrefixCacheTask::class,        // Cache keys: tenant_1_key
    PrefixFilesystemTask::class,   // Storage: storage/app/tenant_1/
    ClearResolvedInstancesTask::class,
    // SwitchDatabaseTask::class,  // Uncomment for multi-database
],

php artisan tenant:create "Acme Corp" --domain=acme.example.com --database=tenant_acme

// config/multitenancy.php
'database' => [
    'strategy' => 'multi',
    'tenant_connection' => 'tenant',
    'landlord_connection' => env('DB_CONNECTION', 'mysql'),
],

use Rylxes\Multitenancy\Facades\Tenant;

// Set current tenant
$tenant = \Rylxes\Multitenancy\Models\Tenant::find(1);
Tenant::makeCurrent($tenant);

// Check current tenant
Tenant::current();   // Returns Tenant model or null
Tenant::check();     // Returns bool

// Run code as a specific tenant
Tenant::execute($tenant, function () {
    // All queries scoped to $tenant here
    $projects = Project::all();
});
// Previous tenant context (or none) is restored after

// Global helper
tenant();            // Returns current Tenant or null

// Forget current tenant
Tenant::forgetCurrent();

use Rylxes\Multitenancy\Testing\ActingAsTenant;

class ProjectTest extends TestCase
{
    use ActingAsTenant;

    public function test_projects_are_scoped_to_tenant(): void
    {
        $tenant = Tenant::create(['name' => 'Test']);
        $this->actingAsTenant($tenant);

        $project = Project::create(['name' => 'My Project']);

        $this->assertEquals($tenant->id, $project->tenant_id);
    }
}

// config/multitenancy.php
return [
    'tenant_model'   => \Rylxes\Multitenancy\Models\Tenant::class,
    'tenant_finder'  => \Rylxes\Multitenancy\Finders\DomainTenantFinder::class,
    'tenant_column'  => 'tenant_id',
    'safeguard'      => true,  // Throw on unscoped tenant queries

    'switch_tenant_tasks' => [
        PrefixCacheTask::class,
        PrefixFilesystemTask::class,
        ClearResolvedInstancesTask::class,
        // SwitchDatabaseTask::class, // Uncomment for multi-DB
    ],

    'database' => [
        'strategy' => 'single', // 'single' or 'multi'
        'tenant_connection' => 'tenant',
        'landlord_connection' => env('DB_CONNECTION', 'mysql'),
    ],

    'cache' => ['prefix_base' => 'tenant_'],
    'filesystem' => [
        'suffix_base' => 'tenant_',
        'disks' => ['local', 'public'],
    ],
];
bash
php artisan vendor:publish --tag=multitenancy-config
php artisan migrate

src/
  TenantManager.php              — Core singleton: makeCurrent/forgetCurrent/execute
  MultitenancyServiceProvider.php — Config, migrations, commands, middleware
  Models/Tenant.php              — Eloquent model
  Facades/Tenant.php             — Facade for TenantManager
  Contracts/TenantFinder.php     — Interface for identification strategies
  Finders/                       — Domain, Subdomain, Path, Header finders
  Concerns/
    BelongsToTenant.php          — Trait: global scope + auto-fill tenant_id
    TenantAware.php              — Trait: iterate commands over tenants
  Scopes/TenantScope.php         — Global scope: WHERE tenant_id = ?
  Tasks/                         — Cache, Filesystem, Database, Instance switching
  Middleware/                    — InitializeTenancy, EnsureTenantSession
  Events/                       — TenantMadeCurrent, Forgotten, Created, Deleted
  Console/Commands/              — 6 tenant management commands
  Testing/ActingAsTenant.php     — Test helper trait