PHP code example of acdphp / laravel-multitenancy

1. Go to this page and download the library: Download acdphp/laravel-multitenancy library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

acdphp / laravel-multitenancy example snippets


use \Acdphp\Multitenancy\Traits\BelongsToTenant;

class Site extends Model
{
    use BelongsToTenant;
    
    protected $fillable = [
        'company_id',
        ...
    ];
}

use \Acdphp\Multitenancy\Traits\BelongsToTenant;

class Product extends Model
{
    use BelongsToTenant;
    
    protected $fillable = [
        'site_id',
        ...
    ];
    
    protected string $scopeTenancyFromRelation = 'site'; // Define to scope from parent model
    
    public function site(): BelongsTo
    {
        return $this->belongsTo(Site::class);
    }
}

use Acdphp\Multitenancy\Facades\Tenancy;

// Create a company and set it as tenant
$company = Company::create(...);
Tenancy::setTenantIdResolver(fn () => $company->id);

// Then proceed to create a user
User::create(...);

use Acdphp\Multitenancy\Facades\Tenancy;

Tenancy::bypassScope();

Route::middleware(['tenancy.scope.bypass'])->get('/resources/all', ...);

use Acdphp\Multitenancy\Facades\Tenancy;

Tenancy::bypassCreating();

Route::middleware(['tenancy.creating.bypass'])->post('your-route', ...);

'tenant_ref_key' => 'company_id',
sh
php artisan vendor:publish --provider="Acdphp\Multitenancy\TenancyServiceProvider"