Appearance
UsesTenantAndUserTables Trait
The UsesTenantAndUserTables
trait provides convenient methods for accessing tenant and user table names in a consistent way across your application.
Features
This trait offers:
- Standardized access to tenant and user table names
- Conditional behavior based on multi-tenancy settings
- Simplified database operations involving users and tenants
Methods
getTenantTable(): string
Gets the table name of the tenant model.
- Returns:
- The database table name of the configured tenant model
- Behavior:
- Instantiates the configured tenant class
- Calls
getTable()
on the instance to get the actual table name
getUserTable(): string
Gets the table name of the user model.
- Returns:
- The database table name of the configured user model
- Behavior:
- Instantiates the configured user class
- Calls
getTable()
on the instance to get the actual table name
hasTenantTable(): bool
Determines if the application is using multi-tenancy.
- Returns:
true
if multi-tenancy is enabledfalse
if multi-tenancy is disabled
- Behavior:
- Calls the
isMultiTenant()
helper function to check configuration
- Calls the
Usage Example
php
<?php
namespace Modules\Blog\Database\Seeders;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use ModuleManager\ModuleManager\Concerns\UsesTenantAndUserTables;
class UserRoleSeeder extends Seeder
{
use UsesTenantAndUserTables;
public function run(): void
{
// Get table names
$userTable = $this->getUserTable();
// Check if we need to handle tenants
if ($this->hasTenantTable()) {
$tenantTable = $this->getTenantTable();
// Multi-tenant logic
DB::table('role_assignments')->insert([
'user_id' => DB::table($userTable)->first()->id,
'tenant_id' => DB::table($tenantTable)->first()->id,
'role' => 'admin',
]);
} else {
// Single-tenant logic
DB::table('role_assignments')->insert([
'user_id' => DB::table($userTable)->first()->id,
'role' => 'admin',
]);
}
}
}
Integration
This trait is commonly used in:
- Database seeders
- Migrations
- Services that need to work with both user and tenant data
- Queries that need to join across user and tenant tables
Notes
- The trait dynamically retrieves table names based on the current configuration
- It automatically adapts to changes in the tenant or user model configuration
- Using this trait avoids hardcoding table names throughout your application
- It correctly handles both multi-tenant and single-tenant application modes