takeshiyu / tenantify
Tenantify is a Laravel package designed to make implementing a multi-tenancy architecture easy and efficient. With Tenantify, you can quickly set up your application to support multiple tenants using a single database, with each tenant being identified by a unique subdomain.
Requires
- php: ^8.1.0|^8.2.0
- illuminate/support: ^9.0|^10.0
Requires (Dev)
- laravel/pint: ^1.9
- mockery/mockery: ^1.5
- orchestra/testbench: ^8.5
- pestphp/pest: ^2.5
- pestphp/pest-plugin-laravel: ^2.0
Conflicts
- phpunit/phpunit: <10.1.0
README
Tenantify is a Laravel package designed to make implementing a lightweight multi-tenancy architecture easy and efficient. With Tenantify, you can quickly set up your application to support multiple tenants using a single database, with each tenant being identified by a unique subdomain.
Features
- Automatic subdomain detection and tenant resolution
- Subdomain-based routing with Laravel route macro
- Tenant-aware query scopes
- Middleware for tenant context and data isolation
Installation
To install Tenantify, follow these simple steps:
- Install the package via Composer:
composer require takeshiyu/tenantify
- Publish the configuration file and model:
php artisan vendor:publish --provider="TakeshiYu\Tenantify\TenantifyServiceProvider"
Configuration
After installing Tenantify, you can configure it according to your application's requirements. Open the config/tenantify.php
file and adjust the settings as needed:
return [ 'tenant_domain' => 'tenantify.test', 'tenant_model' => App\Models\Tenant::class, 'tenant_column' => 'slug', 'tenant_key' => 'tenant_id', ];
Custom Model
By default, Tenantify uses App\Models\Tenant
( configured in config/tenantify.php
) as the tenant model, but you can adjust the default model according to your application's needs. Please make sure to use the TakeshiYu\Tenantify\Concerns\Tenantable
trait in your model.
use TakeshiYu\Tenantify\Concerns\Tenantable; class YourTenantModel extends Model { use Tenantable; }
Query Scopes
To scope your queries correctly, apply the TakeshiYu\Tenantify\Concerns\HasTenancy
trait on your models:
use TakeshiYu\Tenantify\Concerns\HasTenancy; class YourModel extends Model { use HasTenancy; }
Usage
In routes/web.php
file, define your tenant-specific routes using the tenancy
macro:
Route::tenancy(function () { // your tenant routes here ... });
or, assign TakeshiYu\Tenantify\Middleware\ResolveTenant
middleware to your routes or groups:
Route::get('/', fn () => 'ok')->middleware('tenantify.resolve');
Current Tenant
There are several methods available to work with current tenant:
use TakeshiYu\Tenantify\Tenancy; Tenancy::tenant(); // returns current tenant instance Tenancy::id(); // returns current tenant id Tenancy::slug(); // returns current tenant slug
If no tenant is found, it will throw the TenancyNotInitializedException
.
Testing
You can run the package's tests:
composer test
License
Tenantify is open-sourced software licensed under the MIT license.