Skip to content

HasTenant Trait

The HasTenant trait provides comprehensive multi-tenancy support for Eloquent models, automatically managing tenant relationships and applying tenant-specific query scopes.

Features

This trait offers:

  • Automatic tenant relationship setup
  • Automatic tenant ID management (Add automatically to the model on save)
  • Global query scoping by tenant
  • Conditional functionality based on multi-tenancy configuration
  • Helper methods for tenant ID access

Key Methods

bootHasTenant(): void

Boot method that sets up the tenant functionality.

  • Behavior:
    • Only activates when multi-tenancy is enabled
    • Dynamically creates tenant relationships based on configuration
    • Applies the tenant scope globally

applyTenantScope(): void

Applies the tenant scope to the model.

  • Behavior:
    • Adds a global scope that filters queries by the current tenant
    • Only activates when multi-tenancy is enabled

getTenantId(): ?int

Gets the tenant ID for the current model instance.

  • Returns:
    • The tenant ID as an integer, or null if multi-tenancy is disabled
  • Behavior:
    • Retrieves the value from the tenant ID column defined in configuration

Relationships

The trait automatically sets up two tenant relationships:

  1. A named relationship matching the tenant class name (e.g., company(), team())
  2. A generic tenant() relationship as an alias

Both relationships are belongsTo relationships pointing to the configured tenant model.

Usage Example

php
<?php

namespace Modules\Blog\Models;

use Illuminate\Database\Eloquent\Model;
use ModuleManager\ModuleManager\Concerns\HasTenant;

class Post extends Model
{
    use HasTenant;

    protected $fillable = [
        'tenant_id', // Must include the tenant_id column
        'title',
        'content',
        'author_id',
    ];

    // No need to define tenant relationships - they're added automatically
}

Query Behavior

When the trait is used and multi-tenancy is enabled:

  1. All queries will automatically be scoped to the current tenant
  2. New models will automatically be associated with the current tenant
  3. Relationships will respect tenant boundaries

Example:

php
// Will only return posts belonging to the current tenant
$posts = Post::all();

// Will only return posts belonging to the current tenant with the given author
$authorPosts = Post::where('author_id', $authorId)->get();

Notes

  • The trait only activates its functionality when multi-tenancy is enabled in the configuration
  • The tenant ID column name is taken from the module-manager.tenant_id_column configuration
  • The tenant model class is taken from the module-manager.tenant_class configuration
  • The trait works seamlessly with the TenantScope class to provide query filtering