Easily integrate single-database multi tenant features into your Laravel application

Overview

Social Card of Laravel Tenant Aware

Laravel Tenant Aware

Latest Version on Packagist GitHub Tests Action Status GitHub Code Style Action Status Total Downloads

Easily integrate single-database multi tenant features into your Laravel application.

Installation

You can install the package via composer:

composer require maize-tech/laravel-tenant-aware

You can publish the config file with:

php artisan vendor:publish --tag="tenant-aware-config"

This is the contents of the published config file:

return [

    'tenant' => [

        /*
        |--------------------------------------------------------------------------
        | Tenant Model
        |--------------------------------------------------------------------------
        |
        | Here you may specify the fully qualified class name of the tenant model.
        |
        */

        'model' => null,

        /*
        |--------------------------------------------------------------------------
        | Tenant key name
        |--------------------------------------------------------------------------
        |
        | Here you may specify the column name for the tenant identifier.
        | All models using the multi-tenant feature should include this field
        | in their migration.
        |
        */

        'foreign_key_name' => 'tenant_id',

        /*
        |--------------------------------------------------------------------------
        | Actions
        |--------------------------------------------------------------------------
        |
        | Here you may specify the list of actions used to retrieve che current
        | and landlord tenants.
        |
        */

        'actions' => [
            'current' => Maize\TenantAware\Actions\TenantCurrentAction::class,
            'landlord' => Maize\TenantAware\Actions\TenantLandlordAction::class,
            'current_or_landlord' => Maize\TenantAware\Actions\TenantCurrentOrLandlordAction::class,
            'only_current' => Maize\TenantAware\Actions\TenantOnlyCurrentAction::class,
        ],

    ],

    'models' => [
        /*
        |--------------------------------------------------------------------------
        | Global Models
        |--------------------------------------------------------------------------
        |
        | Here you may specify the full list of global models who should return
        | all entities, including the ones related to the landlord tenant.
        |
        */

        'global' => [
            // App\Models\Article::class,
        ],

        'listen' => [

            /*
            |--------------------------------------------------------------------------
            | Set tenant key
            |--------------------------------------------------------------------------
            |
            | Here you may specify the action invoked when creating a multi-tenant
            | model entity.
            | By default, the action sets the tenant field to the current tenant key.
            |
            */

            'creating' => Maize\TenantAware\Listeners\SetTenantKey::class,
        ],
    ],

    'scope' => [

        /*
        |--------------------------------------------------------------------------
        | Scope apply
        |--------------------------------------------------------------------------
        |
        | Here you may override the default scope method applied to all models
        | who belong to a tenant.
        | The default class adds a where constraint to exclude entities not related
        | to the current user's tenant or to the landlord tenant.
        |
        */

        'apply' => Maize\TenantAware\Scopes\ScopeTenantAware::class,

        /*
        |--------------------------------------------------------------------------
        | Scope Methods
        |--------------------------------------------------------------------------
        |
        | Here you may override the default scope methods used to add the
        | where constraints to all models who belong to a tenant.
        |
        */

        'methods' => [
            Maize\TenantAware\Scopes\ScopeOrTenantWhere::class,
            Maize\TenantAware\Scopes\ScopeTenantWhere::class,
            Maize\TenantAware\Scopes\ScopeTenantAware::class,
        ],
    ],
];

Usage

Configuration

Before getting started, make sure to fill in the model and foreign_key_name attributes under config/tenant-aware.php.

Also, don't forget to define your own TenantCurrentAction and TenantLandlordAction actions in order to retrieve both the current and landlord tenants.

For example, if you're using Spatie's laravel-multitenancy package your custom actions could look like this:

<?php

namespace Support\TenantAware;

use Spatie\Multitenancy\Models\Tenant;

class TenantCurrentAction
{
    public function __invoke(): ?Model
    {
        return Tenant::current();
    }
}
<?php

namespace Support\TenantAware;

use Maize\TenantAware\Support\Config;
use Spatie\Multitenancy\Models\Tenant;

class TenantLandlordAction
{
    public function __invoke(): ?Model
    {
        $tenantModel = Config::getTenantModelName();
        $landlordCode = 'landlord'; // get landlord tenant from your config, env, or wherever you defined it

        return app($tenantModel)::query()
            ->firstWhere('code', $landlordCode);
    }
}

Basic

To use the package, add the Maize\TenantAware\BelongsToTenant trait to the models where you want to use the multi-tenant features.

Remember all your multi-tenant models should have the tenant field specified in foreign_key_name attribute under config/tenant-aware.php.

<?php

namespace App\Models;

use Maize\TenantAware\BelongsToTenant;

class User extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'fist_name',
        'last_name',
        'email',
        'tenant_id',
    ];
}

Once done, when querying any of your multi-tenant models you will only retrieve entities under your same tenant.

Let's say, for example, we have this list of users in our database, and the currently authenticated user is part of the tenant 2:

id email tenant_id created_at updated_at
1 [email protected] 2 // //
2 [email protected] 2 // //
3 [email protected] 2 // //
4 [email protected] 3 // //

When querying the User model, you would only get the first three users:

use App\Models\User;

User::all()->modelKeys(); // returns [1, 2, 3]

Querying global entities

Have a model who should handle both global and tenant related entities? No worries!

All you have to do is add the model class name to the models.global attribute under config/tenant-aware.php. Also, make sure your landlord tenant is returned on your custom TenantLandlordAction action class!

'models' => [
    'global' => [
        App\Models\Course::class,
    ],
],

Let's say you have an e-learning multi-tenant platform with both global courses and custom courses for each tenant.

id name tenant_id created_at updated_at
1 Awesome global course A 1 // //
2 Awesome custom course B 2 // //
3 Awesome custom course C 2 // //
4 Awesome custom course D 3 // //

That's what you would get when querying the Course model for a user under tenant 2:

use App\Models\Course;

Course::all()->modelKeys(); // returns [1, 2, 3]

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

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

You might also like...
This Package helps you in laravel application to log all desired activity for each request from request entry point to generate response at a single snapshot.

Laravel Scenario Logger This Package helps you in laravel application to log all desired activity for each request from request entry point to generat

Bring multi themes support to your Laravel application with a full-featured Themes Manager
Bring multi themes support to your Laravel application with a full-featured Themes Manager

Introduction hexadog/laravel-themes-manager is a Laravel package which was created to let you developing multi-themes Laravel application. Installatio

Laravel package to normalize your data before saving into the database.

This package helps you normalize your data in order to save them into the database. The Goal is to having separate classes that handle the data normalization, and thus can be tested independently.

Easy Way to integrate API in you laravel application.

Easy Api Easy Way to integrate API in you laravel application. Installation Guide Install Package using Composer. composer require flutterbuddy1/easy-

A Laravel extension for using a laravel application on a multi domain setting
A Laravel extension for using a laravel application on a multi domain setting

Laravel Multi Domain An extension for using Laravel in a multi domain setting Description This package allows a single Laravel installation to work wi

Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application.

Laravel Segment Laravel Segment is an opinionated, approach to integrating Segment into your Laravel application. Installation You can install the pac

Multi theme support for Laravel application
Multi theme support for Laravel application

Multi theme support for Laravel application This Laravel package adds multi-theme support to your application. It also provides a simple authenticatio

Support multi theme for Laravel application

Very short description of the package This is where your description should go. Try and limit it to a paragraph or two, and maybe throw in a mention o

A Multi User Chat Application With Laravel and Livewire
A Multi User Chat Application With Laravel and Livewire

A Multi User Chat Application With Laravel and Livewire. where you can chat with multiple frinds at the same time. i build this with php Laravel and Livewire.

Comments
Releases(1.0.0)
Owner
H-FARM Innovation
H-FARM Innovation
Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Smeify is a Stable Automated Solution for Airtime and Data businesses in Nigeria, this package helps you integrate smeify easily into your laravel application.

Ogundiran Adewale Charles 2 Jul 27, 2022
Tiny hands is a Laravel multi-tenant boilerplate with SPA and i18n.

About Tiny Hands Tiny hands is a Laravel multi-tenant boilerplate with SPA and i18n using the following technology stack: Backend Laravel 8.0 API with

Bertrand Kintanar 12 Jun 23, 2022
Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups.

Tenancy for Laravel Enabling awesome Software as a Service with the Laravel framework. This is the successor of hyn/multi-tenant. Feel free to show su

Tenancy 1.1k Dec 30, 2022
Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously

Run multiple websites using the same Laravel installation while keeping tenant specific data separated for fully independent multi-domain setups, previously

Tenancy 2.4k Jan 3, 2023
Integrate likes, bookmarks, favorites, reactions and custom made marks into your application

Laravel Markable This package allows you to easily add the markable feature to your application, as for example likes, bookmarks, favorites and so on.

H-FARM Innovation 500 Jan 5, 2023
Rinvex Tenantable is a contextually intelligent polymorphic Laravel package, for single db multi-tenancy.

Rinvex Tenants is a contextually intelligent polymorphic Laravel package, for single db multi-tenancy. You can completely isolate tenants data with ease using the same database, with full power and control over what data to be centrally shared, and what to be tenant related and therefore isolated from others.

Rinvex 80 Oct 21, 2022
Update multiple Laravel Model records, each with it's own set of values, sending a single query to your database!

Laravel Mass Update Update multiple Laravel Model records, each with its own set of values, sending a single query to your database! Installation You

Jorge González 88 Dec 31, 2022
Easily Integrate PingPing APIs in your Laravel Project

PingPing This composer package allows us to easily integrate PingPing APIs in your Laravel project. What is PingPing ? PingPing is the simplest uptime

Bhushan Gaikwad 15 Mar 22, 2022
Taskpm - Run multi tasks by PHP multi process

php-pkg-template Run multi tasks by PHP multi process Install composer composer require phppkg/taskpm Usage github: use the template for quick create

PHPPkg 2 Dec 20, 2021
Laravel Larex lets you translate your whole Laravel application from a single CSV file.

Laravel Larex Translate Laravel Apps from a CSV File Laravel Larex lets you translate your whole Laravel application from a single CSV file. You can i

Luca Patera 68 Dec 12, 2022