acdphp/laravel-multitenancy

Laravel multi-tenancy model scoping and automatic tenancy assignment.

v2.1.1 2023-12-30 08:10 UTC

This package is auto-updated.

Last update: 2024-03-30 00:31:58 UTC


README

Latest Stable Version

Laravel multi-tenancy model scoping and automatic tenancy assignment.

Installation

composer require acdphp/laravel-multitenancy

This package will resolve the current tenant based on the resolved authenticated user's tenant key value.

Model Usage

use \Acdphp\Multitenancy\Traits\BelongsToTenant;

class YourModel extends Model
{
    use BelongsToTenant;
}

Manually setting the tenant

  • In the registration, for example, tenancy isn't set because it's a non-authenticated endpoint. The tenant has to be manually assigned.
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(...);

Bypassing Scope

  • Sometimes, it's needed to bypass scoping when accessing a model that belongs to a tenant.
use Acdphp\Multitenancy\Facades\Tenancy;

Tenancy::bypassScope();
  • Or by using the middleware.
Route::middleware(['tenancy.scope.bypass'])->get('/resources/all', ...);

Bypassing Automatic Tenancy Assignment

  • It's also possible to bypass auto-tenancy assignments.
use Acdphp\Multitenancy\Facades\Tenancy;

Tenancy::bypassCreating();
  • Or by using the middleware.
Route::middleware(['tenancy.creating.bypass'])->post('your-route', ...);

Modifying config

  • Publish config
php artisan vendor:publish --provider="Acdphp\Multitenancy\TenancyServiceProvider"
  • Change the column name to look for tenancy in models.
'tenant_ref_key' => 'company_id',

License

The MIT License (MIT). Please see License File for more information.