PHP code example of our-edu / multi-tenant

1. Go to this page and download the library: Download our-edu/multi-tenant 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/ */

    

our-edu / multi-tenant example snippets


'session' => [
    'helper' => 'getSession',      // Your helper function name
    'tenant_column' => 'tenant_id', // Column on session object
],

use Illuminate\Database\Eloquent\Model;
use Ouredu\MultiTenant\Traits\HasTenant;

class Project extends Model
{
    use HasTenant;
}

// config/multi-tenant.php
'tables' => [
    'projects' => \App\Models\Project::class,
    'invoices' => \App\Models\Invoice::class,
    'orders' => \App\Models\Order::class,
],

return [
    // Your tenant model class (used by DomainTenantResolver)
    'tenant_model' => App\Models\Tenant::class,
    
    // Default tenant column name
    'tenant_column' => 'tenant_id',
    
    // Session configuration (for UserSessionTenantResolver)
    'session' => [
        'helper' => 'getSession',     // Helper function name
        'tenant_column' => 'tenant_id',
    ],
    
    // Header configuration (for HeaderTenantResolver)
    'header' => [
        'name' => 'X-Tenant-ID',      // Header name containing tenant ID
        'routes' => [                  // Routes where header resolution is allowed
            // 'api.external.*',
            // 'api/v1/external/*',
        ],
    ],
    
    // Production app prefix (prepended to excluded routes)
    'production_app_prefix' => env('PRODUCTION_APP_PREFIX'),
    
    // Excluded routes (bypass tenant resolution in middleware)
    // Supports path patterns with wildcards (asterisk matches any segment)
    'excluded_routes' => [
        // API routes: 'api/*/*/health' matches api/v1/ar/health, api/v2/en/health
        // Web routes: 'health' matches /health
    ],
    
    // Domain configuration (for DomainTenantResolver)
    'domain' => [
        'column' => 'domain',
    ],
    
    // Tables mapped to models (for migration, trait command, and query listener)
    'tables' => [
        // 'users' => \App\Models\User::class,
        // 'orders' => \App\Models\Order::class,
    ],
    
    // Query listener (logs queries without tenant_id filter)
    'query_listener' => [
        'enabled' => true,
        'log_channel' => null,  // null = default channel
    ],

    // Validation scope for database rules (exists / unique)
    'validation' => [
        'apply_tenant_scope' => true,
    ],
];

'tables' => [
    'users' => \App\Models\User::class,
    'orders' => \App\Models\Order::class,
],

'query_listener' => [
    'enabled' => env('MULTI_TENANT_QUERY_LISTENER_ENABLED', true),
    'log_channel' => env('MULTI_TENANT_QUERY_LISTENER_CHANNEL'),
    'primary_keys' => ['id', 'uuid'],  // Primary key columns to skip
],

use Ouredu\MultiTenant\Tenancy\TenantContext;

$context = app(TenantContext::class);

// Get current tenant ID
$tenantId = $context->getTenantId();

// Check if tenant exists
if ($context->hasTenant()) {
    // ...
}

// Manually set tenant ID (for testing, jobs, commands)
$context->setTenantId($tenantId);

// Run code in tenant context
$context->runForTenant($tenantId, function () {
    // All queries scoped to this tenant
});

use Ouredu\MultiTenant\Traits\HasTenant;

class Invoice extends Model
{
    use HasTenant;
    
    // Optional: custom tenant column
    public function getTenantColumn(): string
    {
        return 'organization_id';
    }
}

use Illuminate\Support\Facades\Validator;

app(\Ouredu\MultiTenant\Tenancy\TenantContext::class)->setTenantId(10);

$validator = Validator::make($data, [
    'email' => ['

'validation' => [
    'apply_tenant_scope' => true,
],

// In bootstrap/app.php or Kernel.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->alias([
        'tenant' => \Ouredu\MultiTenant\Middleware\TenantMiddleware::class,
    ]);
})

// In routes
Route::middleware('tenant')->group(function () {
    Route::resource('projects', ProjectController::class);
});

// config/multi-tenant.php
'excluded_routes' => [
    // API routes (with version/lang prefix) - use wildcards
    'api/*/*/health',           // matches api/v1/ar/health, api/v2/en/health
    'api/*/*/webhook/*',        // matches api/v1/ar/webhook/ottu, api/v2/en/webhook/stripe
    'api/*/*/public/*',         // matches api/v1/ar/public/docs
    
    // Web routes (without prefix) - exact match
    'health',                   // matches /health
    'login',                    // matches /login
    'register',                 // matches /register
],

// config/multi-tenant.php
'production_app_prefix' => env('PRODUCTION_APP_PREFIX'),

'excluded_routes' => [
    'health',
    'login',
],

use Ouredu\MultiTenant\Exceptions\TenantNotResolvedException;

// Handle in your exception handler
public function render($request, Throwable $e)
{
    if ($e instanceof TenantNotResolvedException) {
        return response()->json(['error' => 'Tenant not found'], 404);
    }
    
    return parent::render($request, $e);
}

// config/multi-tenant.php
'header' => [
    'name' => 'X-Tenant-ID',      // Header name
    'routes' => [
        'api.external.*',          // Route name pattern
        'api/v1/webhook/*',        // URI pattern
    ],
],

class ProcessInvoice implements ShouldQueue
{
    public ?int $tenantId = null;

    public function __construct(public Invoice $invoice)
    {
        $this->tenantId = app(TenantContext::class)->getTenantId();
    }

    public function handle(): void
    {
        // Restore tenant context
        if ($this->tenantId) {
            app(TenantContext::class)->setTenantId($this->tenantId);
        }
        
        // Process invoice...
    }
}

use Ouredu\MultiTenant\Traits\SetsTenantFromPayload;

class PaymentCreatedListener
{
    use SetsTenantFromPayload;

    public function handle(PaymentCreatedEvent $event): void
    {
        // Set tenant from message payload
        // Throws TenantNotFoundException if tenant_id not found and fallback disabled
        $this->setTenantFromPayload($event->payload);

        // Now all queries will be tenant-scoped
        $order = Order::find($event->orderId);
    }
}

'listener' => [
    // Fallback to database when tenant_id not in payload (queries where is_active = true)
    'fallback_to_database' => env('MULTI_TENANT_LISTENER_FALLBACK_DB', false),
],

class GenerateReports extends Command
{
    protected $signature = 'reports:generate {--tenant= : Tenant ID}';

    public function handle(): int
    {
        $tenantId = $this->option('tenant');
        
        if ($tenantId) {
            app(TenantContext::class)->setTenantId((int) $tenantId);
        }
        
        // Generate reports...
        
        return self::SUCCESS;
    }
}

use Ouredu\MultiTenant\Timezone\TenantTimezone;

// HTTP request: the session's `timezone` claim, else the tenant/branch row, else app.timezone
$zone = TenantTimezone::current();

// Jobs, listeners, cron: resolve explicitly from ids (memoized per request/job)
$zone = TenantTimezone::for($tenantId, $branchUuid);   // '*' or null branch → tenant zone

// Render text (push/SMS bodies, PDFs, exports) in the tenant zone
$text = $quiz->end_at->inTenantTz()->format('Y-m-d H:i');           // current tenant
$text = $quiz->end_at->inTenantTz('Africa/Cairo')->format('H:i');   // explicit (jobs/cron)

// Parse an incoming instant: an explicit offset is honoured, naive input is read in the tenant zone
$startsAt = TenantTimezone::parse($request->input('starts_at'));

// AppServiceProvider — where the UserSession is hydrated from /token/claims
$userSession->timezone = $tokenClaims->timezone;

use Ouredu\MultiTenant\Casts\UtcDateTime;

protected $casts = [
    'starts_at' => UtcDateTime::class,   // instant
    'birthdate' => 'date:Y-m-d',         // wall-clock date: never converted, never ISO-serialized
];

use Ouredu\MultiTenant\Traits\SerializesDatesAsIso;

abstract class BaseModel extends Model
{
    use SerializesDatesAsIso;
}

// lang/vendor/multi-tenant/en/exceptions.php
return [
    'tenant_not_resolved' => 'Unable to resolve tenant. No resolver returned a valid tenant ID.',
];

// lang/vendor/multi-tenant/ar/exceptions.php
return [
    'tenant_not_resolved' => 'غير قادر على تحديد المستأجر. لم يُرجع أي محلل معرف مستأجر صالح.',
];

// lang/vendor/multi-tenant/fr/exceptions.php
return [
    'tenant_not_resolved' => 'Impossible de résoudre le locataire. Aucun résolveur n\'a retourné un ID de locataire valide.',
];
bash
php artisan vendor:publish --tag=multi-tenant-lang --force