PHP code example of ubayedtanvir / laravel-tenancy

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

    

ubayedtanvir / laravel-tenancy example snippets


final class Team extends Model implements IsTenant {}

final class Invoice extends Model
{
    use BelongsToTenant;
}

// migration
$table->tenant();   // uuid, ulid, or bigint — figured out from your model

use UbayedTanvir\LaravelTenancy\Contracts\IsTenant;

final class Team extends Model implements IsTenant
{
    use HasUuids; // or HasUlids, or just auto-increment — doesn't matter
}

use UbayedTanvir\LaravelTenancy\Concerns\BelongsToTenant;

final class Invoice extends Model
{
    use BelongsToTenant;
}

Schema::create('invoices', function (Blueprint $table) {
    $table->id();
    $table->tenant();   // foreign key, index, cascade — all wired
    $table->string('number');
    $table->timestamps();

    $table->unique(['team_id', 'number']); // unique per tenant, not globally
});

// bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->group('tenant', [
        \UbayedTanvir\LaravelTenancy\Http\Middleware\IdentifyTenant::class,
        \UbayedTanvir\LaravelTenancy\Http\Middleware\RequireTenant::class,
        \UbayedTanvir\LaravelTenancy\Http\Middleware\EnsureTenantMember::class,
    ]);
})

Route::middleware(['web', 'auth', 'tenant'])
    ->prefix('{tenant}')
    ->as('tenant.')
    ->group(base_path('routes/tenant.php'));

// config/tenancy.php

'resolver' => PathTenantResolver::class,           // /acme/dashboard (default)
// or
'resolver' => HeaderTenantResolver::class,         // X-Tenant: acme
// or
'resolver' => [                                    // chain — first match wins
    HeaderTenantResolver::class,
    PathTenantResolver::class,
],

Tenancy::resolveUsing(fn (Request $r) => Team::where('api_key', $r->bearerToken())->first());

Tenancy::crossTenant(fn () => Invoice::count());

Invoice::query()->forTenant($otherTeam)->get();

Invoice::query()->acrossTenants()->count();

SendInvoiceEmail::dispatch($invoice);     // runs as the current tenant
Mail::to($user)->queue(new InvoiceMail($invoice));
$user->notify(new InvoicePaid($invoice));

use UbayedTanvir\LaravelTenancy\Contracts\NotTenantAware;

final class SendPlatformDigest implements ShouldQueue, NotTenantAware {}

use UbayedTanvir\LaravelTenancy\Concerns\InteractsWithTenants;

#[Signature('reports:rebuild')]
final class RebuildReports extends Command
{
    use InteractsWithTenants;

    protected function handleForTenant(IsTenant $tenant): int
    {
        Report::query()->stale()->each->rebuild();

        return self::SUCCESS;
    }
}

Cache::tenant()->remember('kpis', 300, fn () => $this->computeKpis());
Cache::get('feature-flags');   // still global

use UbayedTanvir\LaravelTenancy\Testing\InteractsWithTenancy;

it('isolates invoices between tenants', function () {
    $this->assertTenantIsolated(
        Invoice::class,
        Team::factory()->create(),
        Team::factory()->create(),
    );
});

final class User extends Authenticatable implements TenantMembership
{
    use HasTenants;
    use TracksCurrentTenant;
}

// migration
$table->currentTenant();   // nullable, nullOnDelete

Route::middleware(['auth', 'tenant.landing'])
    ->get('/dashboard', fn () => abort(404))
    ->name('dashboard');

// When a tenant is deleted, reassign its members:
$team->members->each(fn ($user) => $user->switchToDefault());

final class LegacyOrder extends Model
{
    use BelongsToTenant;

    protected string $tenantForeignKey = 'account_id';
}

$table->tenant('account_id');

tenant()                             // ?IsTenant
tenant_id()                          // int|string|null
Tenancy::current()                   // ?IsTenant
Tenancy::currentOrFail()             // IsTenant or throws
Tenancy::initialized()               // bool
Tenancy::is($tenantOrId)             // bool

Tenancy::initialize($tenant)
Tenancy::end()
Tenancy::runFor($tenant, fn () => …) // runs callback, restores previous
Tenancy::each(fn ($t) => …)          // all tenants, chunked

Tenancy::crossTenant(fn () => …)     // suspends scope
Model::query()->withoutTenancy()
Model::query()->acrossTenants()
Model::query()->forTenant($tenant)

$user->switchTo($tenant)             // record landing preference
$user->switchToDefault()             // switch to first accessible tenant
$user->forgetCurrentTenant()         // clear landing preference
$user->resolveLandingTenant()        // ?IsTenant — self-heals stale prefs

Cache::tenant()->get($key)
Cache::tenant()->put($key, $value)
Cache::tenant()->remember($key, $ttl, $callback)
bash
php artisan tenancy:install
bash
php artisan reports:rebuild --tenant=acme
php artisan reports:rebuild --all --continue-on-error
bash
php artisan tenancy:audit
yaml
php artisan tenancy:audit --fail-on=warn