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;
}
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' => ['
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.',
];