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
});
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;
}