Laravel multi-tenancy model scoping and automatic tenancy assignment.
composer require acdphp/laravel-multitenancy
This package will resolve the current tenant based on the resolved authenticated user's tenant key value.
use \Acdphp\Multitenancy\Traits\BelongsToTenant;
class YourModel extends Model
{
use BelongsToTenant;
}
- 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(...);
- 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', ...);
- 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', ...);
- 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',
The MIT License (MIT). Please see License File for more information.