thiagomeloo/tenant

A package to manage multi-tenant applications in Laravel

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

This package is auto-updated.

Last update: 2024-04-27 03:32:13 UTC


README

Install

  • Install package

        composer require thiagomeloo/tenant
  • Run migrations for creating tables tenants and domains

        php artisan migrate
  • Create folder migrations tenant in database/migrations/tenant/app

        mkdir -p ./database/migrations/tenant/app
  • Publish

    • Config

          php artisan vendor:publish --tag=tenant-config --force
    • Route File

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

Usage

  • Create tenant and domain

    <?php
    
    #create tenant and domain
    $tenant = new Thiagomeloo\Tenant\Models\Tenant();
    $tenant->save();
    $tenant->domains()->create(['domain' => 'test.localhost']);
  • Create migration for tenant

    #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');
        }
    };
  • Create Model for Tenant

        # 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;
    
        }
    
  • Create Route for Tenant

        #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

Events

Event Namespace
Create new Tenant Model Thiagomeloo\Tenant\Events\TenantCreating
Create database Tenant Thiagomeloo\Tenant\Events\TenantDatabaseCreated
Setup Tenant Thiagomeloo\Tenant\EventsTenantSetupExecuted