### Create Users within Each Tenant Database Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md An example of creating a new user within the database of each existing tenant. It utilizes the `runForEach` method on the `Tenant` model, which iterates through all tenants and executes the provided closure for each one. This ensures that user data is correctly isolated per tenant. ```php App\Models\Tenant::all()->runForEach(function () { App\Models\User::factory()->create(); }); ``` -------------------------------- ### Example of Putting and Getting Array Data (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/tenant-storage.blade.md Provides a concrete example of storing an associative array in tenant storage using `put()` and then retrieving it using `get()`. This demonstrates handling more complex data structures within the storage. ```php >>> tenant()->put('foo', ['a' => 'b', 'c' => 'd']); => [ "a" => "b", "c" => "d", ] >>> tenant()->get('foo'); => [ "a" => "b", "c" => "d", ] ``` -------------------------------- ### Database Storage Driver Migrations in Test Setup (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/application-testing.blade.md Illustrates the setup required for the database storage driver in tests. It involves running `migrate:fresh` within the `setUp()` method to ensure the database schema is ready before tests. ```php protected function setUp(): void { parent::setUp(); $this->artisan('migrate:fresh'); // ... } ``` -------------------------------- ### Run Automatic Installation Artisan Command Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/installation.blade.md This artisan command automates the setup process for the stancl/tenancy package. It will prompt you to choose a storage driver (Redis or relational database). ```bash php artisan tenancy:install ``` -------------------------------- ### Create and Initialize Tenant in Test Setup Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/application-testing.blade.md Demonstrates the basic setup for creating a tenant and initializing it within the `setUp()` method of a test case. This is essential for running tests in an isolated tenant environment. ```php protected function setUp(): void { parent::setUp(); tenant()->create('test.localhost'); tenancy()->init('test.localhost'); } ``` -------------------------------- ### Run Database Migrations Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md Applies all pending database migrations, including those generated by the stancl/tenancy package for tenant management. ```bash php artisan migrate ``` -------------------------------- ### Database Driver Setup for Testing Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/application-testing.blade.md Shows how to set up the database for testing when using the database storage driver. It includes running the necessary migrations and then creating and initializing a tenant. ```php protected function setUp(): void { parent::setUp(); $this->call('migrate', [ '--path' => database_path('migrations'), '--database' => 'sqlite', ]); tenant()->create('test.localhost'); tenancy()->init('test.localhost'); } ``` -------------------------------- ### Initialize Tenancy in Test Setup (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/application-testing.blade.md Demonstrates how to create and initialize tenants within the `setUp()` method of a PHP test case. This ensures that tenancy is active for tests. ```php protected function setUp(): void { parent::setUp(); tenancy()->create('test.localhost'); tenancy()->init('test.localhost'); } ``` -------------------------------- ### Install Package via Composer Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/installation.blade.md This command installs the stancl/tenancy package using Composer. Ensure you are using a compatible Laravel version (5.8+). ```bash composer require 'stancl/tenancy:~1.8' ``` -------------------------------- ### Require Package via Composer Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/installation.blade.md Installs the stancl/tenancy package using Composer. This is the initial step for integrating the package into your Laravel project. ```bash composer require stancl/tenancy ``` -------------------------------- ### Redis Driver Setup for Testing Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/application-testing.blade.md Explains how to prepare the Redis database for testing when using the Redis storage driver. It involves flushing the testing connection's database before creating and initializing a tenant. ```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'); } ``` -------------------------------- ### Specify Central Domains in Tenancy Config Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md Configures the list of central domains for your application. These domains will serve the main application content and handle tenant registration. ```php 'central_domains' => [ 'saas.test', // Add the ones that you use. I use this one with Laravel Valet. ], // For Laravel Sail: 'central_domains' => [ '127.0.0.1', 'localhost', ], ``` -------------------------------- ### Create Custom Tenant Model Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md Defines a custom Tenant model that extends the base Tenant model provided by the package and uses traits for database and domain management. This model is crucial for multi-database and domain-specific configurations. ```php \App\Models\Tenant::class, ``` -------------------------------- ### Redis Storage Driver Flush in Test Setup (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/application-testing.blade.md Details the setup for the Redis storage driver in tests. It requires flushing the Redis database using a specific testing connection within the `setUp()` method to prevent data loss. ```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(); // ... } ``` -------------------------------- ### Configure Tenant Database Manager Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/configuration.blade.md Example of mapping a database driver to its corresponding TenantDatabaseManager class in the configuration. ```php 'mysql' => Stancl\Tenancy\TenantDatabaseManagers\MySQLDatabaseManager::class ``` -------------------------------- ### Create Tenants and Domains using Tinker Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md Demonstrates how to create new tenants and associate domains with them using Laravel's Tinker tool. This is a common method for testing tenant creation and domain mapping without a full UI. Each tenant is created with a unique ID and a corresponding domain. ```php $ php artisan tinker >>> $tenant1 = App\Models\Tenant::create(['id' => 'foo']); >>> $tenant1->domains()->create(['domain' => 'foo.localhost']); >>> >>> $tenant2 = App\Models\Tenant::create(['id' => 'bar']); >>> $tenant2->domains()->create(['domain' => 'bar.localhost']); ``` -------------------------------- ### Sample Base TestCase for DB Storage Driver (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/application-testing.blade.md A comprehensive base `TestCase` class for PHPUnit when using the database storage driver. It includes `setUp()` for migrations and configuration, and `tearDown()` for tenant cleanup. It also configures exempt domains. ```php artisan('migrate:fresh'); config([ 'tenancy.queue_database_creation' => false, ]); config(['tenancy.exempt_domains' => [ '127.0.0.1', 'localhost', ]]); } public function tearDown(): void { config([ 'tenancy.queue_database_deletion' => false, 'tenancy.delete_database_after_tenant_deletion' => true, ]); tenancy()->all()->each->delete(); parent::tearDown(); } } ``` -------------------------------- ### PHP Tenant User Creation and Initialization Example Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/synced-resources-between-tenants.blade.md Shows how to initialize a specific tenant and then create a user within that tenant's database using the `User` model. The user is created with the same `global_id` as the central user to establish synchronization. This requires the tenant to be initialized and the `User` model correctly configured. ```php tenancy()->initialize($tenant); // Create the same user in tenant DB $user = User::create([ 'global_id' => 'acme', 'name' => 'John Doe', 'email' => 'john@localhost', 'password' => 'secret', 'role' => 'commenter', // unsynced ]); ``` -------------------------------- ### Configure Middleware Priority in Kernel.php Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/installation.blade.md Sets the middleware priority in Laravel's `app/Http/Kernel.php` file. This ensures that the tenancy middleware executes before other middleware, allowing for timely database connection switching. ```php protected $middlewarePriority = [ \Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class, \Stancl\Tenancy\Middleware\InitializeTenancy::class, // ... ]; ``` -------------------------------- ### Custom Tenancy Bootstrapper Implementation (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/tenancy-bootstrappers.blade.md Provides an example of how to create a custom tenancy bootstrapper by implementing the `TenancyBootstrapper` interface. This allows for custom bootstrapping logic. ```php namespace App; use StanclTenancyContractsTenancyBootstrapper; use StanclTenancyContractsTenant; class MyBootstrapper implements TenancyBootstrapper { public function bootstrap(Tenant $tenant) { // ... } public function revert() { // ... } } ``` -------------------------------- ### Set Tenant-Specific Configuration using PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/event-system.blade.md Demonstrates how to set tenant-specific configuration values by hooking into the 'bootstrapped' event. This example shows how to update a configuration value with data from the current tenant's storage. ```php \Tenancy::bootstrapped(function ($tenantManager) { config(['some.api.key' => $tenantManager->tenant['api_key']); }); ``` -------------------------------- ### Implement StorageDriver Interface in PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/writing-storage-drivers.blade.md This example demonstrates how to create a custom storage driver by implementing the `Stancl\Tenancy\Contracts\StorageDriver` interface in PHP. It includes method signatures for tenant creation, updates, deletion, and retrieval by ID or domain. This serves as a blueprint for integrating custom storage solutions. ```php >> tenancy()->all() => Illuminate\Support\Collection {#3080 all: [ Stancl\Tenancy\Tenant {#3076 +data: [ "id" => "b07aa3b0-dc68-11e9-9352-9159b2055c42", ], +domains: [ "foo.localhost", ], }, Stancl\Tenancy\Tenant {#3075 +data: [ "id" => "b38b2bd0-dc68-11e9-adfc-ede94ab3b264", ], +domains: [ "bar.localhost", ], }, ], } >>> tenancy()->all()->pluck('domains') => Illuminate\Support\Collection {#3108 all: [ [ "foo.localhost", ], [ "bar.localhost", ], ], } ``` -------------------------------- ### PHP Central User Creation Example Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/synced-resources-between-tenants.blade.md Demonstrates how to create a new user in the central database using the `CentralUser` model. This user is intended to be synchronized across multiple tenant databases. It requires the `CentralUser` model to be defined and the necessary database connection configured. The `global_id` attribute is crucial for synchronization. ```php $user = CentralUser::create([ 'global_id' => 'acme', 'name' => 'John Doe', 'email' => 'john@localhost', 'password' => 'secret', 'role' => 'superadmin', // unsynced ]); ``` -------------------------------- ### Get Tenant Database Name - PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenancy-initialization.blade.md Retrieves the database name for the current tenant. It prioritizes a database name specified by `tenancy.database_name_key` in the tenant's data. If not found, it constructs the name using a prefix, the tenant's UUID, and a suffix defined in the tenancy configuration. ```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']; } ``` -------------------------------- ### Custom Tenant-Aware Command Logic (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/tenant-aware-commands.blade.md This example shows how to implement tenant-aware command logic manually. It involves accepting a `tenant_id` argument and then using the `tenancy()->find()` method within the `handle()` method to execute a closure for the specific tenant. This provides granular control over tenant context management. ```php tenancy()->find($this->argument('tenant_id'))->run(function () { // Your actual command code executed within the tenant context }); ``` -------------------------------- ### Tenant-Aware Command with Tenant Options (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/tenant-aware-commands.blade.md This example demonstrates a tenant-aware command that uses the `HasATenantsOption` trait. This trait allows the command to accept multiple tenant IDs via an option (e.g., `--tenants=1,2,3`). By default, if no option is provided, the command will execute for all tenants, simplifying batch operations across the tenant base. ```php class FooCommand extends Command { use TenantAwareCommand, HasATenantsOption; public function handle() { // Command logic here, will run for specified or all tenants } } ``` -------------------------------- ### Tenant Initialization with `tenancy()->init()` Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/usage.blade.md Shows how to initialize a tenant using the `tenancy()->init()` helper function. This is useful for setting up or switching to a specific tenant's context. ```php tenancy()->init(); ``` -------------------------------- ### Tenant Creation with `tenant()->create()` Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/usage.blade.md Demonstrates how to create a new tenant using the `tenant()->create()` helper function. This is a common operation for initializing new tenants within the system. ```php tenant()->create(); ``` -------------------------------- ### Get and Put Data in Tenant Storage (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/tenant-storage.blade.md Demonstrates how to store and retrieve data within tenant storage using the `put()` and `get()` methods on `Tenant` objects. `put()` can accept a single key-value pair or an associative array. `get()` can retrieve a single value by key or multiple values by an array of keys, returning an associative array for multiple keys. ```php $tenant->put('key', 'value'); $tenant->put(['key1' => 'value1', 'key2' => 'value2']); $tenant->get('key'); $tenant->get(['key1', 'key2']); ``` -------------------------------- ### Nix Development Environment Commands Source: https://context7.com/stancl/tenancy-docs/llms.txt Shell commands for interacting with the Nix development environment. These commands allow users to enter the development shell, run development servers with watchers, build for production, and perform reproducible builds. ```bash # Enter development shell with all dependencies nix develop # Run development server with watcher nix run # Build for production (result in build_production/) nix run .#production # Reproducible build (result symlinked from Nix store) nix build # Build for local development (localhost:8000 base URL) nix build .#local # Minimal build (only /docs and /assets) nix build .#minimalLocal ``` -------------------------------- ### Customizing Tenant Identification onFail Logic Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/tenant-identification.blade.md Provides an example of how to customize the behavior when tenant identification fails by modifying the static `$onFail` property of an identification middleware. This example redirects the user to a central domain. ```php \Stancl\Tenancy\Middleware\InitializeTenancyByDomain::$onFail = function ($exception, $request, $next) { return redirect('https://my-central-domain.com/'); }; ``` -------------------------------- ### Tenant Storage Management (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenant-storage.blade.md Manages tenant-specific storage for UUIDs, domains, and configuration using `get()` and `put()` methods. Supports single or multiple keys, with optional tenant UUID specification. `get()` returns values or an array of values, while `put()` returns the stored value(s). ```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); tenancy()->get($key); tenancy()->get($key, $uuid); tenancy()->get(['key1', 'key2']); ``` ```php // Example with arrays: tenant()->put('foo', ['a' => 'b', 'c' => 'd']); tenant()->get('foo'); ``` -------------------------------- ### Get All Tenants Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/tenant-manager.blade.md Retrieves a collection of all tenants, returning each as an array of data. ```APIDOC ## GET /api/tenants ### Description Retrieves a collection of all tenants. Each tenant is represented as an object containing its data and associated domains. ### Method GET ### Endpoint `/api/tenants` ### Response #### Success Response (200) - (array) - A collection of tenant objects. - **data** (object) - An object containing tenant-specific data. - **id** (string) - The tenant's unique identifier. - **domains** (array) - A list of domains associated with the tenant. - (string) - A domain name. #### Response Example ```json [ { "data": { "id": "b07aa3b0-dc68-11e9-9352-9159b2055c42" }, "domains": [ "foo.localhost" ] }, { "data": { "id": "b38b2bd0-dc68-11e9-adfc-ede94ab3b264" }, "domains": [ "bar.localhost" ] } ] ``` ``` -------------------------------- ### Get Current Tenant Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/tenant-manager.blade.md Retrieves the currently active tenant or a specific key from the current tenant's data. ```APIDOC ## GET /api/tenants/current ### Description Retrieves the currently active tenant object or a specific key's value from the current tenant's data. ### Method GET ### Endpoint `/api/tenants/current` #### Query Parameters - **key** (string) - Optional - The specific key to retrieve from the current tenant's data (e.g., 'id'). ### Response #### Success Response (200) - (object|string) - If no key is provided, returns the full tenant object. If a key is provided, returns the value associated with that key. #### Response Example (Full Tenant) ```json { "data": { "id": "b07aa3b0-dc68-11e9-9352-9159b2055c42", "plan": "free" }, "domains": [ "foo.localhost" ] } ``` #### Response Example (Specific Key 'id') ```json "b07aa3b0-dc68-11e9-9352-9159b2055c42" ``` ``` -------------------------------- ### Configure Tenancy Bootstrapper Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/configuration.blade.md Example of configuring a TenancyBootstrapper, mapping an alias to its full class name. Aliases are used in the event system. ```php 'cache' => Stancl\Tenancy\TenancyBootstrappers\CacheTenancyBootstrapper::class ``` -------------------------------- ### Shell Commands for NPM Build Scripts Source: https://context7.com/stancl/tenancy-docs/llms.txt Provides common shell commands to execute the defined NPM scripts for development and production builds. Includes commands for running the watch mode, local development, and production builds, as well as a general build script. ```bash # Development with hot reload npm run watch # Local development build npm run dev # Production build npm run production # Full build with Bash ./build.sh ``` -------------------------------- ### Create a Tenant Instance (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/tenants.blade.md Demonstrates how to create a new tenant instance using Eloquent's create method. This action fires an event that can trigger subsequent actions like database creation. ```php $tenant = Tenant::create([ 'plan' => 'free', ]); ``` -------------------------------- ### Add Tenancy Service Provider to Laravel Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/installation.blade.md Manually add the TenancyServiceProvider to your application's bootstrap providers file. This ensures the tenancy features are bootstrapped by Laravel. ```php return [ App\Providers\AppServiceProvider::class, App\Providers\TenancyServiceProvider::class, // <-- here ]; ``` -------------------------------- ### Create Tenant with Domains and Data (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/creating-tenants.blade.md Demonstrates how to create a new tenant using the Tenant::new() method, specifying domains and custom data. The withDomains() and withData() methods are optional. Ensure database is configured before use. ```php use Stancl\Tenancy\Tenant; Tenant::new() ->withDomains(['tenant1.yourapp.com', 'tenant1.com']) ->withData(['plan' => 'free']) ->save(); ``` -------------------------------- ### Add Middleware to Route Groups Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/installation.blade.md Adds the `PreventAccessFromTenantDomains` middleware to specified route groups in `app/Http/Kernel.php`. This is typically applied to 'web' and potentially 'api' route groups to enforce tenancy restrictions. ```php protected $middlewareGroups = [ 'web' => [ \Stancl\Tenancy\Middleware\PreventAccessFromTenantDomains::class, // ... ], // ... ] ``` -------------------------------- ### Create a New Tenant using Artisan CLI Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/console-commands.blade.md The `tenants:create` command facilitates the creation of new tenants from the command line. You can specify multiple domains using `-d` and set initial data using `=` arguments. ```bash php artisan tenants:create -d aaa.localhost -d bbb.localhost plan=free email=foo@test.local ``` -------------------------------- ### Create Tenant Database Connection Configuration - PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenancy-initialization.blade.md Configures a new 'tenant' database connection. It copies settings from a base connection (default or specified in config) and then sets the database name, handling SQLite paths specifically. This prepares the application to connect to a tenant's database. ```php 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]); } ``` -------------------------------- ### Publish Tenancy Configuration File Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/installation.blade.md This artisan command publishes the stancl/tenancy package's configuration file to your Laravel project's config directory. This allows for customization of the package's behavior. ```bash php artisan vendor:publish --provider='Stancl\Tenancy\TenancyServiceProvider' --tag=config ``` -------------------------------- ### Create Tenant with Domain - PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/creating-tenants.blade.md Creates a new tenant with a specified domain. This is the primary method for tenant instantiation. Ensure the database is configured before use. Returns an array containing tenant details. ```php tenant()->create('tenant1.yourapp.com'); ``` -------------------------------- ### Configure InitializeTenancy Middleware in Kernel Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/installation.blade.md This PHP code snippet shows how to set the InitializeTenancy middleware to top priority in your Laravel application's HTTP kernel. This ensures tenancy is initialized before other middleware. ```php protected $middlewarePriority = [ \Stancl\Tenancy\Middleware\InitializeTenancy::class, // ... ]; ``` -------------------------------- ### Impersonation Redirect with Domain Identification Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/features/user-impersonation.blade.md Redirect the user to the impersonation route using the tenant's primary domain. This example demonstrates how to construct the URL for domain-identified tenants. ```php // Note: This is not part of the package, it's up to you to implement // a concept of "primary domains" if you need them. Or maybe you use // one domain per tenant. The package lets you do anything you want. $domain = $tenant->primary_domain; return redirect("https://{$domain}/impersonate/{$token->token}"); ``` -------------------------------- ### Create Framework Directories for Tenant (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/realtime-facades.blade.md This job is responsible for creating the 'framework/cache' directory within each tenant's storage path. It's necessary when using storage_path() suffixing and real-time facades. It requires the tenant object and runs within the tenant's context. ```php tenant = $tenant; } public function handle() { $this->tenant->run(function ($tenant) { $storage_path = storage_path(); mkdir("$storage_path/framework/cache", 0777, true); }); } } ``` -------------------------------- ### Register Central Routes Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/quickstart.blade.md Defines a routing group that will only be accessible on the specified central domains. This is used for routes that should be available globally, like landing pages or signup forms. ```php // routes/web.php, api.php or any other central route files you have foreach (config('tenancy.central_domains') as $domain) { Route::domain($domain)->group(function () { // your actual routes }); } ``` -------------------------------- ### Initialize Tenancy Manually with Tenant Model - PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/manual-initialization.md This snippet demonstrates how to manually initialize tenancy for a specific tenant by first retrieving the tenant model and then passing it to the `initialize()` method. It requires the `Tenant` model and the `tenancy()` helper function. ```php $tenant = Tenant::find('some-id'); tenancy()->initialize($tenant); ``` -------------------------------- ### Integrate Syntax Highlighting with highlight.js Source: https://context7.com/stancl/tenancy-docs/llms.txt A JavaScript module that integrates highlight.js to provide syntax highlighting for code blocks. It registers support for various languages and then applies highlighting to all `pre code` elements on the page. This enhances the readability of code snippets in documentation. ```javascript // source/_assets/js/main.js import hljs from 'highlight.js/lib/highlight'; // Register language modules hls.registerLanguage('bash', require('highlight.js/lib/languages/bash')); hls.registerLanguage('css', require('highlight.js/lib/languages/css')); hls.registerLanguage('html', require('highlight.js/lib/languages/xml')); hls.registerLanguage('javascript', require('highlight.js/lib/languages/javascript')); hls.registerLanguage('json', require('highlight.js/lib/languages/json')); hls.registerLanguage('php', require('highlight.js/lib/languages/php')); hls.registerLanguage('yaml', require('highlight.js/lib/languages/yaml')); // Apply highlighting to all code blocks document.querySelectorAll('pre code').forEach((block) => { hljs.highlightBlock(block); }); ``` -------------------------------- ### Create Tenant with Single Method (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/creating-tenants.blade.md Shows how to create a tenant using the Tenant::create() static method, providing an array of domains and an associative array for tenant data. This method works with both the Tenant class and the Tenant facade. ```php $domains = ['tenant1.myapp.com', 'tenant1.com']; Tenant::create($domains, [ 'plan' => 'free', ]); ``` -------------------------------- ### Impersonation Redirect with Path Identification Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v3/features/user-impersonation.blade.md Redirect the user to the impersonation route using the tenant's ID as a path prefix. This example shows how to construct the URL for path-identified tenants. ```php // Make sure you use the correct prefix for your routes. return redirect("{$tenant->id}/impersonate/{$token->token}"); ``` -------------------------------- ### Connect to Tenant Database - PHP Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenancy-initialization.blade.md Establishes and uses a new database connection named 'tenant'. It first creates a tenant-specific connection configuration based on a default or specified connection, then updates the database name and finally sets it as the default and reconnects. ```php public function connect(string $database) { $this->createTenantConnection($database); $this->useConnection('tenant'); } ``` -------------------------------- ### Deleting a Tenant (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenant-manager.blade.md Provides examples of how to delete a tenant using its UUID, domain, or by first retrieving the UUID. Note that this method only deletes the tenant's record, not its associated database. ```php >>> tenant()->delete('dbe0b330-1a6e-11e9-b4c3-354da4b4f339'); => true >>> tenant()->delete(tenant()->getTenantIdByDomain('dev.localhost')); => true >>> tenant()->delete(tenant()->findByDomain('localhost')['uuid']); => true ``` -------------------------------- ### Sitemap Generation Listener for Jigsaw (PHP) Source: https://context7.com/stancl/tenancy-docs/llms.txt Automatically generates a sitemap.xml file after the Jigsaw static site is built. It excludes specific paths and adds all other generated output paths to the sitemap. Requires the 'baseUrl' configuration to be set and uses the samdark/sitemap library. The listener needs to be registered in bootstrap.php. ```php // listeners/GenerateSitemap.php namespace App\Listeners; use samdark\sitemap\Sitemap; use TightenCo\Jigsaw\Jigsaw; class GenerateSitemap { protected $exclude = [ '/assets/*', '*/favicon.ico', '*/404', ]; public function handle(Jigsaw $jigsaw) { $baseUrl = $jigsaw->getConfig('baseUrl'); if (!$baseUrl) { echo "\nTo generate a sitemap.xml file, please specify a 'baseUrl' in config.php.\n\n"; return; } $sitemap = new Sitemap($jigsaw->getDestinationPath().'/sitemap.xml'); collect($jigsaw->getOutputPaths()) ->reject(function ($path) { return $this->isExcluded($path); }) ->each(function ($path) use ($baseUrl, $sitemap) { if (!Str::startsWith($path, '/')) { $path = '/' . $path; } $sitemap->addItem(rtrim($baseUrl, '/').$path, time(), Sitemap::DAILY); }); $sitemap->write(); } } // Register in bootstrap.php $events->afterBuild(GenerateSitemap::class); ``` -------------------------------- ### NPM Build Scripts for Development and Production Source: https://context7.com/stancl/tenancy-docs/llms.txt Defines NPM scripts for managing the build process. It includes commands for local development, watching for changes, and building for staging and production environments. These scripts utilize cross-env for setting environment variables and configure Webpack via Laravel Mix. ```json { "scripts": { "dev": "npm run local", "watch": "npm run local -- --watch", "local": "cross-env NODE_ENV=development NODE_OPTIONS=--openssl-legacy-provider node_modules/webpack/bin/webpack.js --progress --hide-modules --env=local --config=node_modules/laravel-mix/setup/webpack.config.js", "staging": "cross-env NODE_ENV=staging NODE_OPTIONS=--openssl-legacy-provider node_modules/webpack/bin/webpack.js --progress --hide-modules --env=staging --config=node_modules/laravel-mix/setup/webpack.config.js", "production": "cross-env NODE_ENV=production NODE_OPTIONS=--openssl-legacy-provider node_modules/webpack/bin/webpack.js --progress --hide-modules --env=production --config=node_modules/laravel-mix/setup/webpack.config.js" } } ``` -------------------------------- ### Initialize and End Tenancy with TenantManager (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v2/tenancy-initialization.blade.md Demonstrates how to use TenantManager methods to initialize and end tenancy. These methods are useful for managing tenant contexts within your application, particularly in CLI environments like `php artisan tinker`. ```php use Stancl\Tenancy\TenantManager; // Initialize tenancy TenantManager::initializeTenancy($tenant); TenantManager::initialize($tenant); TenantManager::init($domain); // End tenancy TenantManager::endTenancy(); TenantManager::end(); ``` -------------------------------- ### Getting Tenant Database Name (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenant-manager.blade.md Shows how to retrieve the name of a tenant's database using the `getDatabaseName()` method, which is useful for performing actions like database deletion before deleting the tenant record. ```php >>> tenant()->getDatabaseName(tenant()->findByDomain('laravel.localhost')) => "tenant67412a60-1c01-11e9-a9e9-f799baa56fd9" ``` -------------------------------- ### Jigsaw Navigation Configuration and Blade Usage (PHP) Source: https://context7.com/stancl/tenancy-docs/llms.txt Defines a multi-level navigation structure for different package versions, linking to documentation pages and external resources. The provided Blade template code iterates through this structure to render navigation links dynamically based on the current page's version. Requires the 'version' and 'link' helpers from the Jigsaw configuration. ```php // navigation.php return [ 'v3' => [ 'GitHub' => 'https://github.com/stancl/tenancy', 'Donate' => 'https://tenancyforlaravel.com/donate', 'Introduction' => [ 'children' => [ 'Introduction' => 'introduction', 'Quickstart' => 'quickstart', 'Installation' => 'installation', 'Configuration' => 'configuration', ], ], 'Concepts' => [ 'children' => [ 'The two applications' => 'the-two-applications', 'Tenants' => 'tenants', 'Domains' => 'domains', 'Event system' => 'event-system', ], ], ], ]; // Usage in Blade templates @foreach ($navigation[$page->version()] as $title => $item) @if (is_string($item)) {{ $title }} @elseif (isset($item['children']))
{{ $title }}
@foreach ($item['children'] as $childTitle => $childPath) {{ $childTitle }} @endforeach @endif @endforeach ``` -------------------------------- ### Getting Tenant ID by Domain (PHP) Source: https://github.com/stancl/tenancy-docs/blob/master/source/docs/v1/tenant-manager.blade.md Illustrates how to retrieve a tenant's ID using its associated domain name. Both `getTenantIdByDomain()` and its alias `getIdByDomain()` achieve this, returning the tenant's unique identifier. ```php >>> tenant()->getTenantIdByDomain('localhost'); => "b3ce3f90-1a88-11e9-a6b0-038c6337ae50" >>> tenant()->getIdByDomain('localhost'); => "b3ce3f90-1a88-11e9-a6b0-038c6337ae50" ```