New routes

This commit is contained in:
Samuel Štancl 2019-09-21 22:10:32 +02:00
parent 478452d1eb
commit ae63f30be6
68 changed files with 346 additions and 215 deletions

View file

@ -0,0 +1,51 @@
---
title: Application Testing
description: Application Testing with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Application Testing {#application-testing}
To test your application with this package installed, you can create tenants in the `setUp()` method of your test case:
```php
protected function setUp(): void
{
parent::setUp();
tenant()->create('test.localhost');
tenancy()->init('test.localhost');
}
```
If you're using the database storage driver, you will also need to run the `create_tenants_table` migration:
```php
protected function setUp(): void
{
parent::setUp();
$this->call('migrate', [
'--path' => database_path('migrations'),
'--database' => 'sqlite',
]);
tenant()->create('test.localhost');
tenancy()->init('test.localhost');
}
```
If you're using the Redis storage driver, flush the database in `setUp()`:
```php
protected function setUp(): void
{
parent::setUp();
// make sure you're using a different connection for testing to avoid losing data
Redis::connection('tenancyTesting')->flushdb();
tenant()->create('test.localhost');
tenancy()->init('test.localhost');
}
```

View file

@ -0,0 +1,56 @@
---
title: Configuration
description: Configuring stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Configuration {#configuration}
The `config/tenancy.php` file lets you configure how the package behaves.
> **Note:** If the `tenancy.php` file doesn't exist in your `config` directory, you can publish it by running `php artisan vendor:publish --provider='Stancl\Tenancy\TenancyServiceProvider' --tag=config`
### `storage_driver, storage` {#storage}
This lets you configure the driver for tenant storage, i.e. what will be used to store information about your tenants. You can read more about this on the [Storage Drivers]({{ $page->link('storage-drivers') }}) page.
Available storage drivers:
- `Stancl\Tenancy\StorageDrivers\RedisStorageDriver`
- `Stancl\Tenancy\StorageDrivers\DatabaseStorageDriver`
### `tenant_route_namespace` {#tenant-route-namespace}
Controller namespace used for routes in `routes/tenant.php`. The default value is the same as the namespace for `web.php` routes.
### `exempt_domains` {#exempt-domains}
If a hostname from this array is visited, the `tenant.php` routes won't be registered, letting you use the same routes as in that file.
### `database` {#database}
The application's default connection will be switched to a new one — `tenant`. This connection will be based on the connection specified in `tenancy.database.based_on`. The database name will be `tenancy.database.prefix + tenant UUID + tenancy.database.suffix`.
You can set the suffix to `.sqlite` if you're using sqlite and want the files to be with the `.sqlite` extension. Conversely, you can leave the suffix empty if you're using MySQL, for example.
### `redis` {#redis}
If `tenancy.redis.tenancy` is set to true, connections listed in `tenancy.redis.prefixed_connections` will be prefixed with `config('tenancy.redis.prefix_base') . $uuid`.
> Note: You need phpredis for multi-tenant Redis.
### `cache` {#cache}
The `CacheManager` instance that's resolved when you use the `Cache` or the `cache()` helper will be replaced by `Stancl\Tenancy\CacheManager`. This class automatically uses [tags](https://laravel.com/docs/master/cache#cache-tags). The tag will look like `config('tenancy.cache.tag_base') . $uuid`.
If you need to store something in global, non-tenant cache,
### `filesystem` {#filesystem}
The `storage_path()` will be suffixed with a directory named `config('tenancy.filesystem.suffix_base') . $uuid`.
The root of each disk listed in `tenancy.filesystem.disks` will be suffixed with `config('tenancy.filesystem.suffix_base') . $uuid`.
For disks listed in `root_override`, the root will be that string with `%storage_path%` replaced by `storage_path()` *after* tenancy has been initialized. All other disks will be simply suffixed with `tenancy.filesystem.suffix_base` + the tenant UUID.
Read more about this on the [Filesystem Tenancy]({{ $page->link('filesystem-tenancy') }}) page.

View file

@ -0,0 +1,64 @@
---
title: Console Commands
description: Console commands with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Console Commands {#console-commands}
The package comes with some artisan commands that will help you during development.
## Migrate {#migrate}
The most important command. To use tenants, you have to be able to migrate their databases.
You can use the `tenants:migrate` command to migrate tenant's databases. You can also specify which tenants' databases should be migrated using the `--tenants` option.
```
php artisan tenants:migrate --tenants=8075a580-1cb8-11e9-8822-49c5d8f8ff23
```
> Note: Tenant migrations must be located in `database/migrations/tenant`.
You can use these commands outside the command line as well. If you want to migrate a tenant's database in a controller, you can use the `Artisan` facade.
```php
$tenant = tenant()->create('tenant1.localhost');
\Artisan::call('tenants:migrate', [
'--tenants' => [$tenant['uuid']]
]);
```
## Rollback & seed {#rollback}
- Rollback: `tenants:rollback`
- Seed: `tenants:seed`
Similarly to [migrate](#migrate), these commands accept a `--tenants` option.
## Run {#run}
You can use the tenants:run command to run your own commands for tenants.
If your command's signature were `email:send {--queue} {--subject=} {body}`, you would run this command like this:
```
php artisan tenants:run email:send --tenants=8075a580-1cb8-11e9-8822-49c5d8f8ff23 --option="queue=1" --option="subject=New Feature" --argument="body=We have launched a new feature. ..."
```
## Tenant list {#tenant-list}
```none
php artisan tenants:list
Listing all tenants.
[Tenant] uuid: dbe0b330-1a6e-11e9-b4c3-354da4b4f339 @ localhost
[Tenant] uuid: 49670df0-1a87-11e9-b7ba-cf5353777957 @ dev.localhost
```
## Selectively clearing tenant cache {#selectively-clearing-tenant-cache}
You can delete specific tenants' cache by using the `--tags` option on `cache:clear`:
```
php artisan cache:clear --tags=tenantdbe0b330-1a6e-11e9-b4c3-354da4b4f339
```
The tag is `config('tenancy.cache.tag_base') . $uuid`.

View file

@ -0,0 +1,30 @@
---
title: Creating Tenants
description: Creating tenants with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Creating Tenants {#creating-tenants}
> **Make sure your database is correctly [configured]({{ $page->link('configuration/#database') }}) before creating tenants.**
To create a tenant, you can use
```php
tenant()->create('tenant1.yourapp.com');
```
> Tip: All domains under `.localhost` are routed to 127.0.0.1 on most operating systems. This is useful for development.
If you want to set some data while creating the tenant, you can pass an array with the data as the second argument:
```php
tenant()->create('tenant2.yourapp.com', [
'plan' => 'free'
]);
```
The `create` method returns an array with tenant information (`uuid`, `domain` and whatever else you supplied).
> Note: Creating a tenant doesn't run [migrations]({{ $page->link('console-commands/#migrate') }}) automatically. You have to do that yourself.

View file

@ -0,0 +1,21 @@
---
title: Custom Database Names
description: Custom Database Names with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Custom Database Names {#custom-database-names}
If you want to specify the tenant's database name, set the `tenancy.database_name_key` configuration key to the name of the key that is used to specify the database name in the tenant storage. You must use a name that you won't use for storing other data, so it's recommended to avoid names like `database` and use names like `_stancl_tenancy_database_name` instead. Then just give the key a value during the tenant creation process:
```php
>>> tenant()->create('example.com', [
'_stancl_tenancy_database_name' => 'example_com'
])
=> [
"uuid" => "49670df0-1a87-11e9-b7ba-cf5353777957",
"domain" => "example.com",
"_stancl_tenancy_database_name" => "example_com",
]
```

View file

@ -0,0 +1,18 @@
---
title: Development
description: Development | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Development {#development}
## Running tests {#running-tests}
### With Docker {#with-docker}
If you have Docker installed, simply run ./test. When you're done testing, run docker-compose down to shut down the containers.
### Without Docker {#without-docker}
If you run the tests of this package, please make sure you don't store anything in Redis @ 127.0.0.1:6379 db#14. The contents of this database are flushed everytime the tests are run.
Some tests are run only if the CI, TRAVIS and CONTINUOUS_INTEGRATION environment variables are set to true. This is to avoid things like bloating your MySQL instance with test databases.

View file

@ -0,0 +1,22 @@
---
title: Difference Between This Package And Others
description: Difference Between This Package And Others | with stancl/tenancy — A Laravel multi-database tenancy package that respects your code.
extends: _layouts.documentation
section: content
---
# Difference Between This Package And Others
A frequently asked question is the difference between this package and [tenancy/multi-tenant](https://github.com/tenancy/multi-tenant).
Packages like tenancy/multi-tenant and tenancy/tenancy give you an API for making your application multi-tenant. They give you a tenant DB connection, traits to apply on your models, a guide on creating your own tenant-aware cache, etc.
This package makes your application multi-tenant automatically and attempts to make you not have to change (m)any things in your code.
## Which one should you use?
Depends on what you prefer.
If you want full control and make your application multi-tenant yourself, use tenancy/multi-tenant.
If you want to focus on writing your application instead of tenancy implementations, use stancl/tenancy.

View file

@ -0,0 +1,9 @@
---
title: Digging Deeper
description: Digging Deeper | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Digging Deeper {#digging-deeper}

View file

@ -0,0 +1,47 @@
---
title: The Event System
description: The Event System | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# The Event System
You can use event hooks to change the behavior of the tenancy boostrapping and tenancy ending processes.
The following events are available:
- `boostrapping`
- `boostrapped`
- `ending`
- `ended`
### Tenant-specific database connection example {#tenant-specific-database-connection-example}
You can hook into these events using `Tenancy::<eventName>`:
```php
\Tenancy::boostrapping(function ($tenantManager) {
if ($tenantManager->tenant['uuid'] === 'someUUID') {
config(['database.connections.someDatabaseConnection' => $tenantManager->tenant['databaseConnection']]);
$tenantManager->database->useConnection('someDatabaseConnection');
return ['database'];
}
});
```
The example above checks whether the current tenant has an uuid of `someUUID`. If yes, it creates a new database connection based on data stored in the tenant's storage. Then it changes the default database connection. Finally, it returns an array of the events that this callback prevents.
The following actions can be prevented:
- database connection switch: `database`
- Redis prefix: `redis`
- CacheManager switch: `cache`
- Filesystem changes: `filesystem`
### Tenant-specific configuration example {#tenant-specific-configuration-example}
Another common use case for events is tenant-specific config:
```php
\Tenancy::bootstrapped(function ($tenantManager) {
config(['some.api.key' => $tenantManager->tenant['api_key']);
});
```

View file

@ -0,0 +1,52 @@
---
title: Filesystem Tenancy
description: Filesystem Tenancy with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Filesystem Tenancy {#filesystem-tenancy}
> Note: It's important to differentiate between storage_path() and the Storage facade. The Storage facade is what you use to put files into storage, i.e. `Storage::disk('local')->put()`. `storage_path()` is used to get the path to the storage directory.
The `storage_path()` will be suffixed with a directory named `config('tenancy.filesystem.suffix_base') . $uuid`.
The root of each disk listed in `tenancy.filesystem.disks` will be suffixed with `config('tenancy.filesystem.suffix_base') . $uuid`.
**However, this alone would cause unwanted behavior.** It would work for S3 and similar disks, but for local disks, this would result in `/path_to_your_application/storage/app/tenant1e22e620-1cb8-11e9-93b6-8d1b78ac0bcd/`. That's not what we want. We want `/path_to_your_application/storage/tenant1e22e620-1cb8-11e9-93b6-8d1b78ac0bcd/app/`.
That's what the `root_override` section is for. `%storage_path%` gets replaced by `storage_path()` *after* tenancy has been initialized. The roots of disks listed in the `root_override` section of the config will be replaced accordingly. All other disks will be simply suffixed with `tenancy.filesystem.suffix_base` + the tenant UUID.
Since `storage_path()` will be suffixed, your folder structure will look like this:
![The folder structure](https://i.imgur.com/GAXQOnN.png)
If you write to these directories, you will need to create them after you create the tenant. See the docs for [PHP's mkdir](http://php.net/function.mkdir).
Logs will be saved to `storage/logs` regardless of any changes to `storage_path()`.
One thing that you **will** have to change if you use storage similarly to the example on the image is your use of the helper function `asset()` (that is, if you use it).
You need to make this change to your code:
```diff
- asset("storage/images/products/$product_id.png");
+ tenant_asset("images/products/$product_id.png");
```
Note that all (public) tenant assets have to be in the `app/public/` subdirectory of the tenant's storage directory, as shown in the image above.
This is what the backend of `tenant_asset()` returns:
```php
// TenantAssetsController
return response()->file(storage_path('app/public/' . $path));
```
With default filesystem configuration, these two commands are equivalent:
```php
Storage::disk('public')->put($filename, $data);
Storage::disk('local')->put("public/$filename", $data);
```
If you want to store something globally, simply create a new disk and *don't* add it to the `tenancy.filesystem.disks` config.

View file

@ -0,0 +1,34 @@
---
title: Getting Started
description: Getting started with stancl/tenancy — A Laravel multi-database tenancy package that respects your code.
extends: _layouts.documentation
section: content
---
# Getting Started {#getting-started}
[**stancl/tenancy**](https://github.com/stancl/tenancy) is a Laravel multi-database tenancy package. It is designed in a way that requires you to make no changes to your codebase. Instead of applying traits on models and replacing every single reference to cache by a reference to a tenant-aware cache, the package lets you write your app without thinking about tenancy. It handles tenancy automatically.
> Note: Filesystem is the only thing that can be a little problematic. Be sure to read [that page]({{ $page->link('filesystem-tenancy') }}).
## How does it work? {#how-does-it-work}
A user visits `client1.yourapp.com`. The package identifies the tenant who this domain belongs to, and automatically does the following:
- switches database connection
- replaces the default cache manager
- switches Redis connection
- changes filesystem root paths
The benefits of this being taken care of by the package are:
- separation of concerns: you should write your app, not tenancy implementations
- reliability: you won't have to fear that you forgot to replace a reference to cache by a tenant-aware cache call. This is something you might worry about if you're implementing tenancy into an existing application.
## What is multi-tenancy? {#what-is-multi-tenancy}
Multi-tenancy is the ability to provide your application to multiple customers (who have their own users and other resources) from a single instance of your application. Think Slack, Shopify, etc.
Multi-tenancy can be single-database and multi-database.
**Single-database tenancy** means that your application uses only a single database. The way this is usually implemented is that instead of having the `id`, `title`, `user_id` and `body` columns in your `posts` table, you will also have a `tenant_id` column. This approach works until you need custom databases for your clients. It's also easy to implement, it basically boils down to having your models use a trait which adds a [global scope](https://laravel.com/docs/master/eloquent#global-scopes).
**Multi-database tenancy**, the type that this package provides, lets you use a separate database for each tenant. The benefits of this approach are scalability, compliance (some clients need to have the database on their server) and mitigation of risks such as showing the wrong tenant's data to a user. The downside is that this model is harder to implement, which is why this package exists.

View file

@ -0,0 +1,18 @@
---
title: Horizon Integration
description: Horizon Integration with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Horizon Integration
> Make sure your queue is [correctly configured]({{ $page->link('jobs-queues') }}) before using Horizon.
Jobs are automatically tagged with the tenant's uuid and domain:
![UUID and domain tags](https://i.imgur.com/K2oWTJc.png)
You can use these tags to monitor specific tenants' jobs:
![Monitoring tags](https://i.imgur.com/qB6veK7.png)

View file

@ -0,0 +1,40 @@
---
title: HTTPS Certificates
description: HTTPS Certificates with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# HTTPS certificates
HTTPS certificates are very easy to deal with if you use the `yourclient1.yourapp.com`, `yourclient2.yourapp.com` model. You can use a wildcard HTTPS certificate.
If you use the model where second level domains are used, there are multiple ways you can solve this.
This guide focuses on nginx.
### 1. Use nginx with the lua module
Specifically, you're interested in the [`ssl_certificate_by_lua_block`](https://github.com/openresty/lua-nginx-module#ssl_certificate_by_lua_block) directive. Nginx doesn't support using variables such as the hostname in the `ssl_certificate` directive, which is why the lua module is needed.
This approach lets you use one server block for all tenants.
### 2. Add a simple server block for each tenant
You can store most of your config in a file, such as `/etc/nginx/includes/tenant`, and include this file into tenant server blocks.
```nginx
server {
include includes/tenant;
server_name foo.bar;
# ssl_certificate /etc/foo/...;
}
```
### Generating certificates
You can generate a certificate using certbot. If you use the `--nginx` flag, you will need to run certbot as root. If you use the `--webroot` flag, you only need the user that runs it to have write access to the webroot directory (or perhaps webroot/.well-known is enough) and some certbot files (you can specify these using --work-dir, --config-dir and --logs-dir).
Creating this config dynamically from PHP is not easy, but is probably feasible. Giving `www-data` write access to `/etc/nginx/sites-available/tenants.conf` should work.
However, you still need to reload nginx configuration to apply the changes to configuration. This is problematic and I'm not sure if there is a simple and secure way to do this from PHP.

View file

@ -0,0 +1,8 @@
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0; url=getting-started">
<title>stancl/tenancy</title>
</head>
</html>

View file

@ -0,0 +1,67 @@
---
title: Installation
description: Installing stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Installation {#getting-started}
Laravel 5.8 or higher is needed.
### Require the package via composer
First you need to require the package using composer:
```
composer require stancl/tenancy
```
### Automatic installation {#automatic-installation}
To install the package, simply run
```
php artisan tenancy:install
```
You will be asked if you want to store your data in Redis or a relational database. You can read more about this on the [Storage Drivers]({{ $page->link('storage-drivers') }}) page.
This will do all the steps listed in the [Manual installation](#manual-installation) section for you.
The only thing you have to do now is create a database/Redis connection. Read the [Storage Drivers]({{ $page->link('storage-drivers') }}) page for information about that.
### Manual installation {#manual-installation}
If you prefer installing the package manually, you can do that too. It shouldn't take more than a minute either way.
#### Setting up middleware
Now open `app/Http/Kernel.php` and make the `InitializeTenancy` middleware top priority, so that it gets executed before anything else, making sure things like the database switch connections soon enough:
```php
protected $middlewarePriority = [
\Stancl\Tenancy\Middleware\InitializeTenancy::class,
// ...
];
```
#### Creating routes
The package lets you have tenant routes and "exempt" routes. Tenant routes are your application's routes. Exempt routes are routes exempt from tenancy — landing pages, sign up forms, and routes for managing tenants.
Routes in `routes/web.php` are exempt, whereas routes in `routes/tenant.php` have the `InitializeTenancy` middleware automatically applied on them.
So, to create tenant routes, put those routes in a new file called `routes/tenant.php`.
#### Configuration
Run the following:
```
php artisan vendor:publish --provider='Stancl\Tenancy\TenancyServiceProvider' --tag=config
```
This creates a `config/tenancy.php`. You can use it to configure how the package works.
Configuration is explained in detail on the [Configuration]({{ $page->link('configuration') }}) page.

View file

@ -0,0 +1,12 @@
---
title: Integrations
description: Integrating stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Integrations {#integrations}
This package naturally integrates well with Laravel packages, since it does not rely on you explicitly specifying database connections.
There are some exceptions, though. [Telescope integration]({{ $page->link('telescope') }}), for example, requires you to change the database connection in `config/telescope.php` to a non-default one, because the default connection is switched to the tenant connection. Some packages should use a central connection for data storage.

View file

@ -0,0 +1,23 @@
---
title: Jobs & Queues
description: Jobs & Queues with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Jobs & Queues {#jobs-queues}
Jobs are automatically multi-tenant, which means that if a job is dispatched while tenant A is initialized, the job will operate with tenant A's database, cache, filesystem, and Redis.
**However**, if you're using the `database` or `redis` queue driver, you have to make a small tweak to your queue configuration.
Open `config/queue.php` and make sure your queue driver has an explicitly set connection. Otherwise it would use the default one, which would cause issues, since `database.default` is changed by the package and Redis connections are prefixed.
**If you're using `database`, add a new line to `queue.connections.database`:**
```php
'connection' => 'mysql',
```
where `'mysql'` is the name of your non-tenant database connection with a `jobs` table.
**If you're using Redis, make sure its `'connection'` is not in `tenancy.redis.prefixed_connections`.**

View file

@ -0,0 +1,20 @@
---
title: Middleware Configuration
description: Middleware Configuration with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Middleware Configuration {#middleware-configuration}
When a tenant route is visited and the tenant can't be identified, an exception is thrown. If you want to change this behavior, to a redirect for example, add this to your `app/Providers/AppServiceProvider.php`'s `boot()` method:
```php
// use Stancl\Tenancy\Middleware\InitializeTenancy;
$this->app->bind(InitializeTenancy::class, function ($app) {
return new InitializeTenancy(function ($exception) {
// return redirect()->route('foo');
});
});
```

View file

@ -0,0 +1,36 @@
---
title: Miscellaneous Tips
description: Miscellaneous Tips | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Miscellaneous Tips {#misc-tips}
## Tenant Redirect {#tenant-redirect}
A customer has signed up on your website, you have created a new tenant and now you want to redirect the customer to their website. You can use the `tenant()` method on Redirect, like this:
```php
// tenant sign up controller
return redirect()->route('dashboard')->tenant($tenant['domain']);
```
## Custom ID scheme
If you don't want to use UUIDs and want to use something more human-readable (even domain concatenated with uuid, for example), you can create a custom class for this:
```php
use Stancl\Tenancy\Interfaces\UniqueIdentifierGenerator;
class MyUniqueIDGenerator implements UniqueIdentifierGenerator
{
public static function handle(string $domain, array $data): string
{
return $domain . \Webpatser\Uuid\Uuid::generate(1, $domain);
}
}
```
and then set the `tenancy.unique_id_generator` config to the full path to your class.

View file

@ -0,0 +1,17 @@
---
title: Stay Updated
description: Stay Updated | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Stay Updated {#stay-updated}
If you'd like to be notified about new versions, you can [sign up for e-mail notifications](https://stancl.github.io/tenancy/#stay-updated) or join our [Telegram channel](https://t.me/joinchat/AAAAAFjdrbSJg0ZCHTzxLA).
You can choose whether you want to receive emails about major versions and/or minor versions.
- Major versions include breaking changes. Composer won't know about these versions and won't update to them. Major versions will be released about once every 6 months.
- Minor versions include backwards-compatible features and bug fixes.
<!-- todo mailchimp dialog -->

View file

@ -0,0 +1,61 @@
---
title: Storage Drivers
description: Storage Drivers of stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Storage Drivers {#storage-drivers}
Storage drivers are used to store a list of all tenants, their domains and any extra information you store about your tenants (e.g. their plan).
Currently, database and Redis storage drivers are available as part of the package. However, you can [write your own]({{ $page->link('writing-storage-drivers') }}) (and contribute ❤️) storage drivers.
## Database {#database}
The database storage driver lets you store tenant information in a relational database like MySQL, PostgreSQL and SQLite.
The benefit of this storage driver is that you don't have to use both Redis and a database for your data. Also you don't have to do as much configuration.
To use this driver, you need to have a `tenants` table. You may also use a custom database connection. By default, `tenancy.storage.db.connection` is set to `central`, which means that the `central` database connection will be used to store tenants. This connection is not automatically created, so you'd have to create it manually. You can create database connections in the `config/database.php` file.
If you'd like to use an existing connection, you can set this config to the name of the connection, e.g. `mysql`.
To create the `tenants` table, you can use the migration that comes with this package. If you haven't published it during installation, publish it now:
```
php artisan vendor:publish --provider='Stancl\Tenancy\TenancyServiceProvider' --tag=migrations
```
By default, all of your data will be stored in the JSON column `data`. If you want to store some data in a dedicated column (to leverage indexing, for example), add the column to the migration and to `tenancy.custom_columns` config.
Finally, run the migration:
```
php artisan migrate
```
> If you use a non-default connection, such as `central`, you have to specify which DB to migrate using the `--database` option.
>
> If you have existing migrations related to your app in `database/migrations`, move them to `database/migrations/tenant`. You can read more about tenant migrations [here]({{ $page->link('console-commands/#migrate') }}).
## Redis {#redis}
The Redis storage driver lets you store tenant information in Redis, a high-performance key-value store.
The benefit of this storage driver is its performance.
**Note that you need to configure persistence on your Redis instance if you don't want to lose all information about tenants.**
Read the [Redis documentation page on persistence](https://redis.io/topics/persistence). You should definitely use AOF and if you want to be even more protected from data loss, you can use RDB **in conjunction with AOF**.
If your cache driver is Redis and you don't want to use AOF with it, run two Redis instances. Otherwise, just make sure you use a different database (number) for tenancy and for anything else.
To use this driver, create a new Redis connection in the `database.redis` configuration (`config/database.php`) called `tenancy`.
```php
'tenancy' => [
'host' => env('TENANCY_REDIS_HOST', '127.0.0.1'),
'password' => env('TENANCY_REDIS_PASSWORD', null),
'port' => env('TENANCY_REDIS_PORT', 6380), // different port = separate Redis instance
'database' => env('TENANCY_REDIS_DB', 3), // alternatively, different database number
],
```

View file

@ -0,0 +1,29 @@
---
title: Telescope Integration
description: Telescope Integration with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Telescope Integration
Requests in Telescope are automatically tagged with the tenant uuid and domain:
![Telescope Request with tags](https://i.imgur.com/CEEluYj.png)
This lets you filter requests by uuid and domain:
![Filtering by uuid](https://i.imgur.com/SvbOa7S.png)
![Filtering by domain](https://i.imgur.com/dCJuEr1.png)
If you'd like to set Telescope tags in your own code, e.g. in your `AppServiceProvider`, replace your `Telescope::tag()` call like this:
```php
\Tenancy::integrationEvent('telescope', function ($entry) {
return ['abc']; // your logic
});
```
![Tenancy tags merged with tag abc](https://i.imgur.com/4p1wOiM.png)
Once Telescope 3 is released, you won't have to do this.
To have Telescope working, make sure your `telescope.storage.database.connection` points to a non-tenant connection. It's that way by default, so for most projects, Telescope should work out of the box.

View file

@ -0,0 +1,152 @@
---
title: Tenancy Initialization
description: Tenancy Initialization with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Tenancy Initialization {#tenancy-initialization}
Tenancy can be initialized by calling `tenancy()->init()`. The `InitializeTenancy` middleware calls this method automatically.
You can end a tenancy session using `tenancy()->end()`. This is useful if you need to run multiple tenant sessions or a mixed tenant/non-tenant session in a single request/command.
The `tenancy()->init()` method calls `bootstrap()`.
This method switches database connection, Redis connection (if Redis tenancy is enabled), cache and filesystem root paths.
This page goes through the code that actually makes this happen. You don't have to read this page to use the package, but it will give you insight into the magic that's happening in the background, so that you can be more confident in it.
## Database tenancy {#database-tenancy}
`bootstrap()` runs the following method:
```php
public function switchDatabaseConnection()
{
$this->database->connect($this->getDatabaseName());
}
```
If `tenancy.database_name_key` is set and present in the current tenant's data, the `getDatabaseName()` returns the stored database_name. Otherwise it returns the prefix + uuid + suffix.
```php
public function getDatabaseName($tenant = []): string
{
$tenant = $tenant ?: $this->tenant;
if ($key = $this->app['config']['tenancy.database_name_key']) {
if (isset($tenant[$key])) {
return $tenant[$key];
}
}
return $this->app['config']['tenancy.database.prefix'] . $tenant['uuid'] . $this->app['config']['tenancy.database.suffix'];
}
```
This is passed as an argument to the `connect()` method. This method creates a new database connection and sets it as the default one.
```php
public function connect(string $database)
{
$this->createTenantConnection($database);
$this->useConnection('tenant');
}
public function createTenantConnection(string $database_name)
{
// Create the `tenant` database connection.
$based_on = config('tenancy.database.based_on') ?: config('database.default');
config()->set([
'database.connections.tenant' => config('database.connections.' . $based_on),
]);
// Change DB name
$database_name = $this->getDriver() === 'sqlite' ? database_path($database_name) : $database_name;
config()->set(['database.connections.tenant.database' => $database_name]);
}
public function useConnection(string $connection)
{
// $this->database = Illuminate\Database\DatabaseManager
$this->database->setDefaultConnection($connection);
$this->database->reconnect($connection);
}
```
## Redis tenancy {#redis-tenancy}
The `bootstrap()` method calls `setPhpRedisPrefix()` if `tenancy.redis.tenancy` is `true`.
This method cycles through the `tenancy.redis.prefixed_connections` and sets their prefix to `tenancy.redis.prefix_base` + uuid.
```php
public function setPhpRedisPrefix($connections = ['default'])
{
// [...]
foreach ($connections as $connection) {
$prefix = $this->app['config']['tenancy.redis.prefix_base'] . $this->tenant['uuid'];
$client = Redis::connection($connection)->client();
try {
// [...]
$client->setOption($client::OPT_PREFIX, $prefix);
} catch (\Throwable $t) {
throw new PhpRedisNotInstalledException();
}
}
}
```
## Cache tenancy {#cache-tenancy}
`bootstrap()` calls `tagCache()` which replaces the `'cache'` key in the service container with a different `CacheManager`.
```php
public function tagCache()
{
// [...]
$this->app->extend('cache', function () {
return new \Stancl\Tenancy\CacheManager($this->app);
});
}
```
This `CacheManager` forwards all calls to the inner store, but also adds tag which "scope" the cache and allow for selective cache clearing:
```php
class CacheManager extends BaseCacheManager
{
public function __call($method, $parameters)
{
$tags = [config('tenancy.cache.tag_base') . tenant('uuid')];
if ($method === 'tags') {
if (\count($parameters) !== 1) {
throw new \Exception("Method tags() takes exactly 1 argument. {count($parameters)} passed.");
}
$names = $parameters[0];
$names = (array) $names; // cache()->tags('foo') https://laravel.com/docs/5.7/cache#removing-tagged-cache-items
return $this->store()->tags(\array_merge($tags, $names));
}
return $this->store()->tags($tags)->$method(...$parameters);
}
}
```
## Filesystem tenancy {#filesystem-tenancy}
`bootstrap()` calls `suffiexFilesystemRootPaths()`. This method changes `storage_path()` and the roots of disks listed in `config('tenancy.filesystem.disks)`. You can read more about this on the [Filesystem Tenancy]({{ $page->link('filesystem-tenancy') }}) page.
```php
public function suffixFilesystemRootPaths()
{
// [...]
$suffix = $this->app['config']['tenancy.filesystem.suffix_base'] . tenant('uuid');
// storage_path()
$this->app->useStoragePath($old['path'] . "/{$suffix}");
// Storage facade
foreach ($this->app['config']['tenancy.filesystem.disks'] as $disk) {
// [...]
if ($root = \str_replace('%storage_path%', storage_path(), $this->app['config']["tenancy.filesystem.root_override.{$disk}"])) {
Storage::disk($disk)->getAdapter()->setPathPrefix($root);
} else {
$root = $this->app['config']["filesystems.disks.{$disk}.root"];
Storage::disk($disk)->getAdapter()->setPathPrefix($root . "/{$suffix}");
}
}
// [...]
}
```

View file

@ -0,0 +1,112 @@
---
title: Tenant Manager
description: Tenant Manager | stancl/tenancy — A Laravel multi-database tenancy package that respects your code.
extends: _layouts.documentation
section: content
---
# Tenant Manager {#tenant-manager}
This page documents a couple of other `TenantManager` methods you may find useful.
### Finding tenant using UUID
`find()` is an alias for `getTenantById()`. You may use the second argument to specify the key(s) as a string/array.
```php
>>> tenant()->find('dbe0b330-1a6e-11e9-b4c3-354da4b4f339');
=> [
"uuid" => "dbe0b330-1a6e-11e9-b4c3-354da4b4f339",
"domain" => "localhost",
"foo" => "bar",
]
>>> tenant()->find('dbe0b330-1a6e-11e9-b4c3-354da4b4f339', 'foo');
=> [
"foo" => "bar",
]
>>> tenant()->getTenantById('dbe0b330-1a6e-11e9-b4c3-354da4b4f339', ['foo', 'domain']);
=> [
"foo" => "bar",
"domain" => "localhost",
]
```
### Getting tenant ID by domain
```php
>>> tenant()->getTenantIdByDomain('localhost');
=> "b3ce3f90-1a88-11e9-a6b0-038c6337ae50"
>>> tenant()->getIdByDomain('localhost');
=> "b3ce3f90-1a88-11e9-a6b0-038c6337ae50"
```
### Finding tenant by domain
You may use the second argument to specify the key(s) as a string/array.
```php
>>> tenant()->findByDomain('localhost');
=> [
"uuid" => "b3ce3f90-1a88-11e9-a6b0-038c6337ae50",
"domain" => "localhost",
]
```
### Accessing the array
You can access the public array tenant of TenantManager like this:
```php
tenancy()->tenant
```
which is an array. If you want to get the value of a specific key from the array, you can use one of the helpers the key on the tenant array as an argument.
```php
tenant('uuid'); // Does the same thing as tenant()->tenant['uuid']
```
### Getting all tenants
This method returns a collection of arrays.
```php
>>> tenant()->all();
=> Illuminate\Support\Collection {#2980
all: [
[
"uuid" => "32e20780-1a88-11e9-a051-4b6489a7edac",
"domain" => "localhost",
],
[
"uuid" => "49670df0-1a87-11e9-b7ba-cf5353777957",
"domain" => "dev.localhost",
],
],
}
>>> tenant()->all()->pluck('domain');
=> Illuminate\Support\Collection {#2983
all: [
"localhost",
"dev.localhost",
],
}
```
### Deleting a tenant
```php
>>> tenant()->delete('dbe0b330-1a6e-11e9-b4c3-354da4b4f339');
=> true
>>> tenant()->delete(tenant()->getTenantIdByDomain('dev.localhost'));
=> true
>>> tenant()->delete(tenant()->findByDomain('localhost')['uuid']);
=> true
```
This doesn't delete the tenant's database. If you want to delete it, save the database name prior to deleting the tenant. You can get the database name using `getDatabaseName()`
```php
>>> tenant()->getDatabaseName(tenant()->findByDomain('laravel.localhost'))
=> "tenant67412a60-1c01-11e9-a9e9-f799baa56fd9"
```

View file

@ -0,0 +1,34 @@
---
title: Tenant Routes
description: Tenant routes with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Tenant Routes {#tenant-routes}
Routes within `routes/tenant.php` will have the `web` middleware group and the `IntializeTenancy` middleware automatically applied on them. This middleware attempts to identify the tenant based on the current hostname. Once the tenant is identified, the database connection, cache, filesystem root paths and, optionally, Redis connection, will be switched.
Just like `routes/web.php`, these routes use the `App\Http\Controllers` namespace.
> If a tenant cannot be identified, anexception will be thrown. If you want to change this behavior (to a redirect, for example) read the [Middleware Configuration]({{ $page->link('middleware-configuration') }}) page.
## Exempt routes {#exempt-routes}
Routes outside the `routes/tenant.php` file will not have the tenancy middleware automatically applied on them. You can apply this middleware manually, though.
If you want some of your, say, API routes to be multi-tenant, simply wrap them in a Route group with this middleware:
```php
use Stancl\Tenancy\Middleware\InitializeTenancy;
Route::middleware(InitializeTenancy::class)->group(function () {
// Route::get('/', 'HelloWorld');
});
```
## Using the same routes for tenant and non-tenant parts of the application {#using-the-same-routes-for-tenant-and-non-tenant-parts-of-the-application}
The `Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains` middleware makes sure 404 is returned when a user attempts to visit a web route on a tenant (non-exempt) domain.
The install command applies this middleware to the `web` group. If you want to do this for another route group, add this middleware manually to that group. You can do this in `app/Http/Kernel.php`.

View file

@ -0,0 +1,48 @@
---
title: Tenant Storage
description: Tenant storage with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Tenant Storage {#tenant-storage}
Tenant storage is where tenants' uuids and domains are stored. You can store things like the tenant's plan, subscription information, and tenant-specific application configuration in tenant storage. You can use these functions:
```php
get (string|array $key, string $uuid = null) // $uuid defaults to the current tenant's UUID
put (string|array $key, mixed $value = null, string $uuid = null) // if $key is array, make sure $value is null
```
To put something into the tenant storage, you can use `put()` or `set()`.
```php
tenancy()->put($key, $value);
tenancy()->set($key, $value); // alias for put()
tenancy()->put($key, $value, $uuid);
tenancy()->put(['key1' => 'value1', 'key2' => 'value2']);
tenancy()->put(['key1' => 'value1', 'key2' => 'value2'], null, $uuid);
```
To get something from the storage, you can use `get()`:
```php
tenancy()->get($key);
tenancy()->get($key, $uuid);
tenancy()->get(['key1', 'key2']);
```
> Note: `tenancy()->get(['key1', 'key2'])` returns an array with values only
Note that $key has to be a string or an array with string keys. The value(s) can be of any data type. Example with arrays:
```php
>>> tenant()->put('foo', ['a' => 'b', 'c' => 'd']);
=> [ // put() returns the supplied value(s)
"a" => "b",
"c" => "d",
]
>>> tenant()->get('foo');
=> [
"a" => "b",
"c" => "d",
]
```

View file

@ -0,0 +1,20 @@
---
title: Usage
description: Usage | stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Usage {#usage}
This chapter describes usage of the package. That includes creating tenants, deleting tenants, storing data in the tenant storage.
Most pages will use the `tenancy()` helper function. This package comes with two helpers - `tenancy()` and `tenant()`. They do the same thing, so you can use the one that reads better given its context.
`tenant()->create()` reads better than `tenancy()->create()`, but `tenancy()->init()` reads better than `tenant()->init()`.
You can pass an argument to the helper function to get a value out of the tenant storage. `tenant('plan')` is identical to [`tenant()->get('plan')`]({{ $page->link('tenant-storage') }}).
The package also comes with two facades. `Tenancy` and `Tenant`. Use what feels the best.
Both the helpers and the facades resolve the `TenantManager` from the service container.

View file

@ -0,0 +1,80 @@
---
title: Writing Storage Drivers
description: Writing Storage Drivers with stancl/tenancy — A Laravel multi-database tenancy package that respects your code..
extends: _layouts.documentation
section: content
---
# Writing Storage Drivers
If you don't want to use the provided DB/Redis storage drivers, you can write your own driver.
To create a driver, create a class that implements the `Stancl\Tenancy\Interfaces\StorageDriver` interface.
For historical reasons, the `TenantManager` will try to json encode/decode data coming from the storage driver. If you want to avoid this, set `public $useJson = false;`. That will make `TenantManager` encode/decode only `put()` and `get()` data, so that data types can be stored correctly.
The DB storage driver has `public $useJson = false;`, while the Redis storage driver doesn't use this property, so it's false by default.
Here's an example:
```php
namespace App\StorageDrivers\MongoDBStorageDriver;
use Stancl\Tenancy\Interfaces\StorageDriver;
class MongoDBStorageDriver implements StorageDriver
{
public $useJson = false;
public function identifyTenant(string $domain): array
{
//
}
public function getAllTenants(array $uuids = []): array
{
//
}
public function getTenantById(string $uuid, array $fields = []): array
{
//
}
public function getTenantIdByDomain(string $domain): ?string
{
//
}
public function createTenant(string $domain, string $uuid): array
{
//
}
public function deleteTenant(string $uuid): bool
{
//
}
public function get(string $uuid, string $key)
{
//
}
public function getMany(string $uuid, array $keys): array
{
//
}
public function put(string $uuid, string $key, $value)
{
//
}
public function putMany(string $uuid, array $values): array
{
//
}
}
```