thiagomeloo/tenant

用于管理Laravel中多租户应用的包

dev-main 2023-10-27 02:29 UTC

This package is auto-updated.

Last update: 2024-09-27 04:27:25 UTC


README

安装

  • 安装包

        composer require thiagomeloo/tenant
  • 运行迁移以创建表 tenantsdomains

        php artisan migrate
  • database/migrations/tenant/app 中创建迁移文件夹 tenant

        mkdir -p ./database/migrations/tenant/app
  • 发布

    • 配置

          php artisan vendor:publish --tag=tenant-config --force
    • 路由文件

          php artisan vendor:publish --tag=tenant-routes --force 

用法

  • 创建租户和域名

    <?php
    
    #create tenant and domain
    $tenant = new Thiagomeloo\Tenant\Models\Tenant();
    $tenant->save();
    $tenant->domains()->create(['domain' => 'test.localhost']);
  • 为租户创建迁移

    #database/migrations/tenant/app
    <?php
    
    use Illuminate\Database\Migrations\Migration;
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Support\Facades\Schema;
    
    return new class extends Migration
    {
        /**
         * Run the migrations.
         */
        public function up(): void
        {
            Schema::create('products', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->timestamps();
            });
        }
    
        /**
         * Reverse the migrations.
         */
        public function down(): void
        {
            Schema::dropIfExists('products');
        }
    };
  • 为租户创建模型

        # app/Models/Product.php
        <?php
    
        namespace App\Models;
    
        use Illuminate\Database\Eloquent\Factories\HasFactory;
        use Illuminate\Database\Eloquent\Model;
    
        class Product extends Model
        {
    
            use HasFactory;
    
        }
    
  • 为租户创建路由

        #routes/tenants/web.php
        
        use Illuminate\Support\Facades\Route;
    
        Route::get('example', function () {
            dd("Ok"); 
        }); #output: ok
    
        Route::get('save-product-example', function(){
            Product::create(['name' => 'Product 1']);
            dd("Ok");
        }); #output: ok

事件