PHP code example of manggala / tenancy

1. Go to this page and download the library: Download manggala/tenancy 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/ */

    

manggala / tenancy example snippets


return [
    // Mode: 'single-db', 'multi-db', atau 'hybrid'
    'mode' => env('TENANCY_MODE', 'single-db'),

    // Kolom ID tenant untuk Single-DB mode
    'tenant_column' => 'tenant_id',

    // Central domain yang diabaikan dari resolusi tenant
    'central_domains' => [
        'app.test',
        'localhost',
        '127.0.0.1',
    ],
];

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Manggala\Tenancy\Traits\BelongsToTenant;

class Invoice extends Model
{
    use BelongsToTenant; // Auto-inject WHERE tenant_id = 'xxx' & auto-fill tenant_id on create
}

use Manggala\Tenancy\Http\Middleware\IdentifyTenantBySubdomain;

Route::middleware(['web', IdentifyTenantBySubdomain::class])->group(function () {
    Route::get('/dashboard', [DashboardController::class, 'index']);
});

use Manggala\Tenancy\Http\Middleware\IdentifyTenantByHeader;

Route::middleware(['api', IdentifyTenantByHeader::class])->group(function () {
    Route::get('/v1/orders', [OrderApiController::class, 'index']);
});

use Manggala\Tenancy\Facades\Tenancy;

// Dapatkan tenant aktif saat ini
$current = Tenancy::current();

// Jalankan closure dalam konteks tenant lain sementara waktu
Tenancy::runFor($targetTenant, function () {
    // Semua query Eloquent & storage path di sini mengacu ke $targetTenant
    Invoice::create([
        'title' => 'Cross-tenant Invoice',
        'amount' => 500000,
    ]);
});
// Setelah block ini selesai, konteks otomatis kembali ke $current

$tenant = Tenancy::current();

if ($tenant->canUseFeature('export_pdf')) {
    // Fitur diperbolehkan
}

if ($tenant->hasExceededQuota('max_users', User::count())) {
    return response()->json(['error' => 'Quota user telah penuh.'], 403);
}
bash
php artisan tenancy:install
bash
php artisan migrate
bash
composer analyse