Laravel Multi Tenant
A general purpose multi-tenancy package for Laravel 4.2+. Accidentally derived from the work of @tonydew, and with help from @rizqidjamaluddin
Note: This is an experimental package. We're figuring out the best way to do this, together. Please have a play, but don't expect it to work perfectly right now. Pull requests welcome :)
Installation
First off, this package assumes that you have a column on all of your tenant-scoped tables that references which tenant each row belongs to.
For example, you might have a companies
table, and all your other tables might have a company_id
column (with a foreign key, right?).
To get started, require this package in your composer.json and run composer update:
"aura-is-here/laravel-multi-tenant": "dev-master"
After updating composer, add the ServiceProvider to the providers array in app/config/app.php
'AuraIsHere\LaravelMultiTenant\LaravelMultiTenantServiceProvider',
You should also publish the config file:
php artisan config:publish aura-is-here/laravel-multi-tenant
and set up your tenant_column
setting.
Usage
First off, you'll have to call TenantScope::setTenantId($tenantId)
at some point. It could be as part of your login process, or in an oAuth setup method, or wherever.
You can also call TenantScope::setTenantId($tenantId)
again at any point to change the tenant that is scoped.
Warning: If you haven't yet set a tenant id, or if you unset the tenant id (TenantScope::setTenantId(null)
), your requests will not be scoped. This can be useful, but it's a good thing to be aware of.
Once you've got that all worked out, simply use
the trait in all your models that you'd like to scope by tenant:
<?php
use AuraIsHere\LaravelMultiTenant\ScopedByTenant;
class Model extends Eloquent {
use ScopedByTenant;
}
Henceforth, all operations against that model will be scoped automatically.
$models = Model::all(); // Only the Models with the correct tenant id
$model = Model::find(1); // Will fail if the Model with `id` 1 belongs to a differant tenant
$newModel = Model::create(); // Will have the tenant id added automatically
If you need to run queries across all tenants, you can do it easily:
$allModels = Model::allTenants()->get(); //You can run any fluent query builder methods here, and they will not be scoped by tenant
When you are developing a multi tenanted application, it can be confusing sometimes why you keep getting ModelNotFound
exceptions.
Laravel Multi Tenant will catch those exceptions, and re-throw them as ModelNotFoundForTenant
, to help you out :)
Contributing
Please! This is not yet a complete solution, but there's no point in all of us re-inventing this wheel over and over. If you find an issue, or have a better way to do something, open an issue or a pull request.