1. Go to this page and download the library: Download acdphp/laravel-multitenancy 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/ */
acdphp / laravel-multitenancy example snippets
'tenant_ref_key' => 'company_id',
'auto_resolve_tenant_id' => true,
'auto_assign_tenant_id' => true,
use \Acdphp\Multitenancy\Traits\BelongsToTenant;
class Site extends Model
{
use BelongsToTenant;
protected $fillable = [
'company_id',
...
];
}
use \Acdphp\Multitenancy\Traits\BelongsToTenant;
class Site extends Model
{
use BelongsToTenant;
protected string $tenantRefKey = 'org_id'; // Override the global tenant_ref_key for this model
protected $fillable = [
'org_id',
...
];
}
use \Acdphp\Multitenancy\Traits\BelongsToTenant;
class Product extends Model
{
use BelongsToTenant;
protected $fillable = [
'site_id',
...
];
protected string $scopeTenancyFromRelation = 'site'; // Define to scope from parent model
public function site(): BelongsTo
{
return $this->belongsTo(Site::class);
}
}
use \Acdphp\Multitenancy\Traits\BelongsToTenant;
class Event extends Model
{
use BelongsToTenant;
protected function applyTenantScope(Builder $builder, array|int|string $tenantId): void
{
$builder->where(function (Builder $query) use ($tenantId) {
$query->where('is_public', true)
->orWhereIn('company_id', (array) $tenantId);
});
}
}
class Ticket extends Model
{
use BelongsToTenant;
protected string $scopeTenancyFromRelation = 'event'; // Ticket is visible when its event is
public function event(): BelongsTo
{
return $this->belongsTo(Event::class);
}
}
use Acdphp\Multitenancy\Facades\Tenancy;
// Create a company and set it as tenant
$company = Company::create(...);
Tenancy::setTenantIdResolver(fn () => $company->id);
// Then proceed to create a user
User::create(...);
use Acdphp\Multitenancy\Facades\Tenancy;
// Scope to a single tenant
Tenancy::setScopingTenantIdResolver(fn () => $tenantId);
// Scope to multiple tenants
Tenancy::setScopingTenantIdResolver(fn () => [1, 2, 3]);
use Acdphp\Multitenancy\Facades\Tenancy;
Tenancy::bypassScope();