Token导航 LogoToken导航TokenDH.com
研究检索需要联网github未标认证来源可访问许可证需确认审计通过

laravel-multi-tenancyLaravel multi tenancy 搜索

Agent Skill

laravel-multi-tenancy 用于查找、检索和筛选相关信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要根据关键词、任务场景或来源线索快速定位候选结果时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

326

周安装

14

GitHub Stars

5

下载量

114
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:laravel-multi-tenancy(Laravel multi tenancy 搜索)
来源仓库:https://github.com/leeovery/agentic-skills
仓库路径:skills/laravel-multi-tenancy
安装命令:
npx skills add https://github.com/leeovery/agentic-skills --skill laravel-multi-tenancy
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/leeovery/agentic-skills --skill laravel-multi-tenancy

简介

laravel-multi-tenancy 用于查找、检索和筛选 Laravel 多租户架构相关资料,适合在开发或迁移项目中参考实现方案。

  • 适用于需要了解租户隔离策略、数据库划分、中间件处理或多租户包选型的场景。
  • 通过 npx skills add 命令从 GitHub 仓库安装,需确认是否涉及网络请求或文件系统操作。
  • 建议结合原始 README 验证功能细节,并评估对现有项目的影响与维护活跃度。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Laravel Multi-Tenancy

Multi-tenancy separates application logic into central (non-tenant) and tenanted (tenant-specific) contexts.

Related guides:

Philosophy

Multi-tenancy provides:

  • Clear separation between central and tenant contexts
  • Database isolation with separate databases per tenant
  • Automatic scoping of queries to current tenant
  • Context awareness through helper classes
  • Queue integration with tenant context preservation

When to Use

Use multi-tenancy when:

  • Building SaaS applications with complete data isolation
  • Each customer needs their own database
  • Compliance requires strict data separation

Don't use when:

  • Simple user segmentation is sufficient (use user_id scoping)
  • All customers share the same schema
  • Application complexity doesn't justify the overhead

Directory Structure

app/
├── Actions/
│   ├── Central/          # Non-tenant actions
│   │   ├── Tenant/
│   │   │   ├── CreateTenantAction.php
│   │   │   └── DeleteTenantAction.php
│   │   └── User/
│   │       └── CreateCentralUserAction.php
│   └── Tenanted/         # Tenant-specific actions
│       ├── Order/
│       │   └── CreateOrderAction.php
│       └── Customer/
│           └── CreateCustomerAction.php
├── Data/
│   ├── Central/          # Central DTOs
│   └── Tenanted/         # Tenant DTOs
├── Http/
│   ├── Central/          # Central routes (tenant management)
│   ├── Web/              # Tenant application routes
│   └── Api/              # Public API (tenant-scoped)
├── Models/               # All models in standard location
│   ├── Tenant.php        # Central model
│   ├── Order.php         # Tenanted model
│   └── Customer.php
└── Services/
    └── Tenancy/
        ├── Landlord.php
        └── Facades/
            └── Landlord.php

Central Actions

Central actions manage tenants and cross-tenant operations.

<?php

declare(strict_types=1);

namespace App\Actions\Central\Tenant;

use App\Data\Central\CreateTenantData;
use App\Models\Tenant;
use Illuminate\Support\Facades\DB;

class CreateTenantAction
{
    public function __construct(
        private readonly CreateTenantDatabaseAction $createDatabase,
    ) {}

    public function __invoke(CreateTenantData $data): Tenant
    {
        return DB::transaction(function () use ($data): Tenant {
            $this->guard($data);
            $tenant = $this->createTenant($data);
            ($this->createDatabase)($tenant);
            return $tenant;
        });
    }

    private function guard(CreateTenantData $data): void
    {
        throw_if(
            Tenant::where('domain', $data->domain)->exists(),
            TenantDomainAlreadyExistsException::forDomain($data->domain)
        );
    }

    private function createTenant(CreateTenantData $data): Tenant
    {
        return Tenant::create([
            'id' => $data->tenantId,
            'name' => $data->name,
            'domain' => $data->domain,
        ]);
    }
}

Tenanted Actions

Tenanted actions operate within a specific tenant's context. All queries automatically scoped.

<?php

declare(strict_types=1);

namespace App\Actions\Tenanted\Order;

use App\Data\Tenanted\CreateOrderData;
use App\Models\Order;
use App\Models\User;
use Illuminate\Support\Facades\DB;

class CreateOrderAction
{
    public function __invoke(User $user, CreateOrderData $data): Order
    {
        return DB::transaction(function () use ($user, $data): Order {
            // Automatically scoped to current tenant
            $order = $user->orders()->create([
                'status' => $data->status,
                'total' => $data->total,
            ]);

            $this->createOrderItems($order, $data->items);
            return $order;
        });
    }

    private function createOrderItems(Order $order, array $items): void
    {
        foreach ($items as $item) {
            $order->items()->create([
                'product_id' => $item->productId,
                'quantity' => $item->quantity,
                'price' => $item->price,
            ]);
        }
    }
}

Landlord Helper

Wrap Stancl Tenancy in a Landlord service class for a cleaner API:

<?php

declare(strict_types=1);

namespace App\Services\Tenancy;

use App\Models\Tenant;

class Landlord
{
    public static function tenant(): ?Tenant
    {
        return tenant();
    }

    public static function initialize(Tenant|int|string $tenant): void
    {
        tenancy()->initialize($tenant);
    }

    public static function end(): void
    {
        tenancy()->end();
    }

    public static function runAsCentral(callable $callback): mixed
    {
        return tenancy()->central($callback);
    }

    public function tenantId(): ?string
    {
        return tenant()?->getTenantKey();
    }

    public function eachTenant(callable $callback): void
    {
        Tenant::each(function (Tenant $tenant) use ($callback): void {
            $this->runAs($tenant, $callback);
        });
    }

    public function runAs(Tenant|int|string $tenant, callable $callback): mixed
    {
        if (! $tenant instanceof Tenant) {
            $tenant = tenancy()->find($tenant);
        }

        return tenancy()->run($tenant, $callback);
    }
}

Usage:

use App\Services\Tenancy\Landlord;

$tenant = Landlord::tenant();
$tenantId = Landlord::tenantId();

if (Landlord::tenant() !== null) {
    // Tenant-specific logic
}

Landlord::runAs($tenant, function () {
    Order::create([...]);
});

Landlord::runAsCentral(function () {
    Tenant::create([...]);
});

Tenant Identification Middleware

Domain-Based

use Stancl\Tenancy\Middleware\InitializeTenancyByDomain;

class IdentifyTenant extends InitializeTenancyByDomain
{
    // Tenant identified by domain (e.g., tenant1.myapp.com)
}

Subdomain-Based

use Stancl\Tenancy\Middleware\InitializeTenancyBySubdomain;

class IdentifyTenant extends InitializeTenancyBySubdomain
{
    // Tenant identified by subdomain
}

Header-Based

use Stancl\Tenancy\Middleware\InitializeTenancyByRequestData;

class IdentifyTenant extends InitializeTenancyByRequestData
{
    public static string $header = 'X-Tenant';
}

Route Configuration

Tenant Routes

// routes/tenant.php
Route::middleware(['tenant'])->group(function () {
    Route::get('/orders', [OrderController::class, 'index']);
    Route::post('/orders', [OrderController::class, 'store']);
});

Central Routes

// routes/central.php
Route::middleware(['central'])->prefix('central')->group(function () {
    Route::get('/tenants', [TenantController::class, 'index']);
    Route::post('/tenants', [TenantController::class, 'store']);
});

Bootstrap Configuration

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(function () {
        Route::middleware('web')
            ->prefix('central')
            ->name('central.')
            ->group(base_path('routes/central.php'));

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

Models

All models live in app/Models/. Central vs tenanted distinguished by traits/interfaces, not subdirectories.

Central Model

<?php

declare(strict_types=1);

namespace App\Models;

use Stancl\Tenancy\Database\Models\Tenant as BaseTenant;

class Tenant extends BaseTenant
{
    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }
}

Tenanted Model

<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    // Automatically scoped to current tenant
    // No tenant_id needed in queries

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }
}

Queue Jobs with Tenant Context

Jobs must preserve tenant context when queued.

<?php

declare(strict_types=1);

namespace App\Jobs\Tenanted;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Stancl\Tenancy\Contracts\TenantWithDatabase;
use Stancl\Tenancy\Jobs\TenantAwareJob;

class ProcessOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, TenantAwareJob;

    public function __construct(
        public TenantWithDatabase $tenant,
        public OrderData $orderData,
    ) {
        $this->onQueue('orders');
    }

    public function handle(ProcessOrderAction $action): void
    {
        // Runs in tenant context automatically
        $action($this->orderData);
    }
}

Dispatching:

ProcessOrderJob::dispatch(Landlord::tenant(), $orderData);

Common Patterns

Running Code in Multiple Tenants

// Using Landlord's eachTenant helper
resolve(Landlord::class)->eachTenant(function () {
    Order::where('status', 'pending')->update(['processed' => true]);
});

// Or manually for specific tenants
$tenants = Tenant::all();
foreach ($tenants as $tenant) {
    resolve(Landlord::class)->runAs($tenant, function () {
        Order::where('status', 'pending')->update(['processed' => true]);
    });
}

Accessing Central Data from Tenant Context

Landlord::runAsCentral(function () {
    $allTenants = Tenant::all();
});

Conditional Logic Based on Tenant

if (Landlord::tenant() !== null) {
    $orders = Order::all(); // Scoped to tenant
} else {
    $tenants = Tenant::all(); // Central
}

Testing

→ Complete testing guide: tenancy-testing.md

Includes:

  • Testing central and tenanted actions
  • ManagesTenants and RefreshDatabaseWithTenant traits
  • TenantTestCase setup
  • Pest configuration for multi-tenancy
  • Test directory structure

Best Practices

  • Use directory structure to separate central and tenanted actions/DTOs
  • Keep models in app/Models/ following Laravel convention
  • Always use Landlord helper for tenant access
  • Test both central and tenant contexts separately
  • Preserve tenant context in queued jobs

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.81%
按下载量换算40

Claude

27%
按下载量换算31

Cursor

20.53%
按下载量换算23

Gemini CLI

8.84%
按下载量换算10

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills