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.

v1.0.2 2023-04-23 10:30 UTC

This package is auto-updated.

Last update: 2024-08-23 13:46:07 UTC


README

GitHub Workflow Status GitHub Latest Version Total Downloads

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:

  1. Install the package via Composer:
composer require takeshiyu/tenantify
  1. 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.