### Upgrade Laravel Multitenancy Package Version Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/upgrade-guide.md This command upgrades the `spatie/laravel-multitenancy` package to version `4.0` or higher, which is the first step in the upgrade process to utilize the new contract-based tenant system. ```bash composer require spatie/laravel-multitenancy:^4.0 ``` -------------------------------- ### Publish Laravel Multitenancy Configuration File Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md Execute this Artisan command to publish the default configuration file for the Spatie Laravel Multitenancy package. This creates a `multitenancy.php` file in your `config` directory, allowing you to customize package behavior. ```bash php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-config" ``` -------------------------------- ### Publishing and Migrating Landlord Database for Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-a-single-database.md This command sequence publishes the essential migrations for the Spatie\Multitenancy package and then executes them. This process creates the `tenants` table, which is crucial for storing configuration details for each tenant within the single database setup. ```bash php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-migrations" php artisan migrate --path=database/migrations/landlord ``` -------------------------------- ### Install Spatie Laravel Multitenancy Package via Composer Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md This command installs the Spatie Laravel Multitenancy package using Composer. It adds the package as a dependency to your Laravel project, making its functionalities available for use. ```bash composer require "spatie/laravel-multitenancy:^4.0" ``` -------------------------------- ### Execute Tenant-Aware Artisan Commands Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/making-artisan-commands-tenant-aware.md Examples of executing a tenant-aware Artisan command. The command can run for all tenants by default or for a specific tenant by providing its ID. ```bash php artisan your-favorite-command ``` ```bash php artisan your-favorite-command --tenant=1 ``` -------------------------------- ### Handling Tenant Context in Test Setup with User Login (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Modifies the `TestCase.php` setup to explicitly make a tenant current in the `setUp` method. This is necessary when a user login is performed using the `Auth` facade in the `setUp` method, as automatic tenant switching might not occur otherwise. ```php protected function setUp(): void { parent::setUp(); Event::listen(MadeTenantCurrentEvent::class, function () { $this->beginDatabaseTransaction(); }); Tenant::first()->makeCurrent(); } ``` -------------------------------- ### Configure Global Tenant Session Middleware in Laravel Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md Demonstrates how to add the `EnsureValidTenantSession` and `NeedsTenant` middleware globally in `bootstrap/app.php` to protect all tenant-aware routes against cross-tenant abuse. This ensures that a user's session is always tied to the correct tenant, responding with a 401 if a mismatch occurs. ```php // in `bootstrap/app.php` return Application::configure(basePath: dirname(__DIR__)) // ... ->withMiddleware(function (Middleware $middleware) { $middleware ->web(append: [ \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class, \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class, ]); }); ``` -------------------------------- ### Seed Tenant Databases and Differentiate Seeder Logic Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This snippet shows how to seed tenant databases using the `tenants:artisan` command. It also provides a PHP example of a `DatabaseSeeder` that uses `Tenant::checkCurrent()` to conditionally run tenant-specific or landlord-specific seeders, ensuring proper data isolation. ```bash php artisan tenants:artisan "migrate --database=tenant --seed" ``` ```php use Illuminate\Database\Seeder; use Spatie\Multitenancy\Models\Tenant; class DatabaseSeeder extends Seeder { public function run() { Tenant::checkCurrent() ? $this->runTenantSpecificSeeders() : $this->runLandlordSpecificSeeders(); } public function runTenantSpecificSeeders() { // run tenant specific seeders } public function runLandlordSpecificSeeders() { // run landlord specific seeders } } ``` -------------------------------- ### Implement SwitchTenantTask for Cache Prefixing in PHP Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/creating-your-own-task.md This example class, `PrefixCacheTask`, demonstrates how to implement `SwitchTenantTask` to dynamically change the cache prefix based on the current tenant. The `makeCurrent` method sets a tenant-specific prefix, while `forgetCurrent` restores the original prefix, ensuring proper cache isolation. It also handles forgetting the cache driver to apply the new prefix immediately. ```php namespace Spatie\Multitenancy\Tasks; use Spatie\Multitenancy\Contracts\IsTenant; class PrefixCacheTask implements SwitchTenantTask { public function __construct(protected ?string $originalPrefix = null) { $this->originalPrefix ??= config('cache.prefix'); } public function makeCurrent(IsTenant $tenant): void { $this->setCachePrefix("tenant_{$tenant->id}"); } public function forgetCurrent(): void { $this->setCachePrefix($this->originalPrefix); } protected function setCachePrefix(string $prefix): void { config()->set('cache.prefix', $prefix); $storeName = config('cache.default'); app('cache')->forgetDriver($storeName); } } ``` -------------------------------- ### Define Custom Tenant Middleware Group in Laravel Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md Shows how to create a named middleware group, 'tenant', in `bootstrap/app.php` that includes `NeedsTenant` and `EnsureValidTenantSession`. This approach is suitable when only a subset of routes are tenant-aware, allowing for selective application of tenant protection. ```php // in `bootstrap/app.php` return Application::configure(basePath: dirname(__DIR__)) // ... ->withMiddleware(function (Middleware $middleware) { $middleware ->group('tenant', [ \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class, \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class, ]); }); ``` -------------------------------- ### Default Configuration for Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md This PHP code block displays the default content of the `config/multitenancy.php` file. It defines various settings such as tenant finder, switch tenant tasks, tenant model, queue awareness, database connections, and custom actions for the multitenancy package. ```php null, /* * These fields are used by tenant:artisan command to match one or more tenant. */ 'tenant_artisan_search_fields' => [ 'id', ], /* * These tasks will be performed when switching tenants. * * A valid task is any class that implements Spatie\Multitenancy\Tasks\SwitchTenantTask */ 'switch_tenant_tasks' => [ // \Spatie\Multitenancy\Tasks\PrefixCacheTask::class, // \Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class, // \Spatie\Multitenancy\Tasks\SwitchRouteCacheTask::class, ], /* * This class is the model used for storing configuration on tenants. * * It must extend `Spatie\Multitenancy\Models\Tenant::class` or * implement `Spatie\Multitenancy\Contracts\IsTenant::class` interface */ 'tenant_model' => Tenant::class, /* * If there is a current tenant when dispatching a job, the id of the current tenant * will be automatically set on the job. When the job is executed, the set * tenant on the job will be made current. */ 'queues_are_tenant_aware_by_default' => true, /* * The connection name to reach the tenant database. * * Set to `null` to use the default connection. */ 'tenant_database_connection_name' => null, /* * The connection name to reach the landlord database. */ 'landlord_database_connection_name' => null, /* * This key will be used to associate the current tenant in the context */ 'current_tenant_context_key' => 'tenantId', /* * This key will be used to bind the current tenant in the container. */ 'current_tenant_container_key' => 'currentTenant', /** * Set it to `true` if you like to cache the tenant(s) routes * in a shared file using the `SwitchRouteCacheTask`. */ 'shared_routes_cache' => false, /* * You can customize some of the behavior of this package by using your own custom action. * Your custom action should always extend the default one. */ 'actions' => [ 'make_tenant_current_action' => MakeTenantCurrentAction::class, 'forget_current_tenant_action' => ForgetCurrentTenantAction::class, 'make_queue_tenant_aware_action' => MakeQueueTenantAwareAction::class, 'migrate_tenant' => MigrateTenantAction::class, ], /* * Jobs tenant aware even if these don't implement the TenantAware interface. */ 'tenant_aware_jobs' => [ // ... ], /* * Jobs not tenant aware even if these don't implement the NotTenantAware interface. */ 'not_tenant_aware_jobs' => [ // ... ], ]; ``` -------------------------------- ### Configuring Database Transactions for Tenant Connections in Tests (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Provides the recommended `TestCase.php` setup for Laravel applications using the `DatabaseTransactions` trait with `spatie/laravel-multitenancy`. This configuration ensures that database transactions are performed on both the landlord and tenant connections, and that a new transaction begins when a tenant is made current. ```php namespace Tests; use Illuminate\Foundation\Testing\DatabaseTransactions; use Illuminate\Foundation\Testing\TestCase as BaseTestCase; use Illuminate\Support\Facades\Event; use Spatie\Multitenancy\Concerns\UsesMultitenancyConfig; use Spatie\Multitenancy\Events\MadeTenantCurrentEvent; abstract class TestCase extends BaseTestCase { use CreatesApplication, DatabaseTransactions, UsesMultitenancyConfig; protected function connectionsToTransact() { return [ $this->landlordDatabaseConnectionName(), $this->tenantDatabaseConnectionName(), ]; } protected function setUp(): void { parent::setUp(); Event::listen(MadeTenantCurrentEvent::class, function () { $this->beginDatabaseTransaction(); }); } } ``` -------------------------------- ### Update Custom Tenant Finder for IsTenant Contract Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/upgrade-guide.md When using a custom tenant finder, the `findForRequest` method must now return an instance of `?IsTenant` instead of the old `Tenant` model. This change reflects the new contract-based approach for resolving the correct tenant instance. ```php use Illuminate\Http\Request; use Spatie\Multitenancy\Contracts\IsTenant; class YourCustomTenantFinder extends TenantFinder { public function findForRequest(Request $request): ?IsTenant { // ... } } ``` -------------------------------- ### Implement IsTenant Interface for Custom Tenant Model Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/using-a-custom-tenant-model.md This example demonstrates how to use an existing model, like Laravel Jetstream's `Team` model, as a tenant model by implementing the `IsTenant` interface and using the `ImplementsTenant` trait. ```php namespace App\Models; use Laravel\Jetstream\Team as JetstreamTeam; use Spatie\Multitenancy\Contracts\IsTenant; use Spatie\Multitenancy\Models\Concerns\ImplementsTenant; class Team extends JetstreamTeam implements IsTenant { use HasFactory; use UsesLandlordConnection; use ImplementsTenant; } ``` -------------------------------- ### Apply Custom Tenant Middleware Group to Laravel Routes Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/base-installation.md Illustrates how to apply a previously defined 'tenant' middleware group to a set of routes in a Laravel routes file. This ensures that all routes within the group are protected by the `NeedsTenant` and `EnsureValidTenantSession` middleware, preventing cross-tenant access. ```php // in a routes file Route::middleware('tenant')->group(function() { // routes }); ``` -------------------------------- ### Update Custom SwitchTenantTask Interface Parameter Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/upgrade-guide.md Custom tasks that implement the `SwitchTenantTask` interface must update the `makeCurrent` method's parameter type. The parameter should now be `IsTenant $tenant` instead of `Tenant $tenant` to align with the new contract. ```php public function makeCurrent(IsTenant $tenant): void; ``` -------------------------------- ### Inject Dependencies in SwitchTenantTask Constructor (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/creating-your-own-task.md This example demonstrates how to inject dependencies into a `SwitchTenantTask`'s constructor using Laravel's service container. It's important to ensure that injected dependency variable names do not conflict with any parameters passed from the `multitenancy` config file. This enables tasks to leverage other services and components within the application. ```php namespace App\Support\SwitchTenantTasks\YourTask use Spatie\Multitenancy\Tasks\SwitchTenantTask; class SwitchTenantDatabaseTask implements SwitchTenantTask { public function __construct(string $name, string $anotherName, MyDepencency $myDependency) { // do something } } ``` -------------------------------- ### Illustrate Tenant-Specific Cache Behavior with Prefixing Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/prefixing-cache.md This PHP example showcases the practical effect of the `PrefixCacheTask`. It demonstrates how cache entries are isolated per tenant: setting a key under one tenant makes it inaccessible to others, and returning to the original state (no tenant) or a specific tenant retrieves the correct, tenant-scoped value. This behavior is achieved by dynamically changing the cache prefix. ```php cache()->put('key', 'original-value'); $tenant->makeCurrent(); cache('key') // returns null; cache()->put('key', 'value-for-tenant'); $anotherTenant->makeCurrent(); cache('key') // returns null; cache()->put('key', 'value-for-another-tenant'); Tenant::forgetCurrent(); cache('key') // returns 'original-value'; $tenant->makeCurrent(); cache('key') // returns 'value-for-tenant' $anotherTenant->makeCurrent(); cache('key') // returns 'value-for-another-tenant' ``` -------------------------------- ### Retrieve Current Tenant in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/working-with-the-current-tenant.md Learn how to get the currently active tenant instance. This can be done directly through the `Tenant::current()` static method, via the `app(IsTenant::class)::current()` service container binding, or by accessing the `app('currentTenant')` key in the container. Returns `null` if no tenant is current. ```php // Model Tenant::current(); // returns the current tenant, or if no tenant is current, `null` // Service Container app(IsTenant::class)::current(); // returns the current tenant, or if no tenant is current, `null` ``` ```php app('currentTenant'); // returns the current tenant, or if no tenant is current, `null` ``` -------------------------------- ### Clear All Application Facade Instances on Tenant Switch in Laravel Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/using-tenant-specific-facades.md This PHP class, also named `ClearFacadeInstancesTask`, provides a more comprehensive solution to clear all resolved facade instances within the `App` namespace when a tenant is forgotten. It automatically discovers all facades that are subclasses of `Illuminate\Support\Facades\Facade` and start with 'App' or 'Facades\App', ensuring a clean state for all application-defined facades. ```php namespace App\Tenancy\SwitchTasks; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Str; use Spatie\Multitenancy\Contracts\IsTenant; use Spatie\Multitenancy\Tasks\SwitchTenantTask; class ClearFacadeInstancesTask implements SwitchTenantTask { public function makeCurrent(IsTenant $tenant): void { // tenant is already current } public function forgetCurrent(): void { $this->clearFacadeInstancesInTheAppNamespace(); } protected function clearFacadeInstancesInTheAppNamespace(): void { // Discovers all facades in the App namespace and clears their resolved instance: collect(get_declared_classes()) ->filter(fn ($className) => is_subclass_of($className, Facade::class)) ->filter(fn ($className) => Str::startsWith($className, 'App') || Str::startsWith($className, 'Facades\\App')) ->each(fn ($className) => $className::clearResolvedInstance( $className::getFacadeAccessor() )); } } ``` -------------------------------- ### Publish Landlord Database Migration Files Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This Bash command publishes the default migration file for the landlord database. It creates a migration in 'database/migrations/landlord' responsible for setting up the 'tenants' table. ```bash php artisan vendor:publish --provider="Spatie\\Multitenancy\\MultitenancyServiceProvider" --tag="multitenancy-migrations" ``` -------------------------------- ### Run Laravel Multitenancy Package Tests Source: https://github.com/spatie/laravel-multitenancy/blob/main/README.md This command executes the test suite for the Laravel multitenancy package. Before running, ensure the required local MySQL databases (`laravel_mt_landlord`, `laravel_mt_tenant_1`, `laravel_mt_tenant_2`) are created to facilitate the tests. ```bash composer test ``` -------------------------------- ### Define SwitchTenantTask Interface in PHP Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/creating-your-own-task.md This interface defines the contract for tenant switching tasks in Spatie's Laravel Multitenancy package. It requires `makeCurrent` to apply tenant-specific logic when a tenant is made current, and `forgetCurrent` to restore the original environment when a tenant is forgotten. Tasks are singletons, allowing state preservation. ```php namespace Spatie\Multitenancy\Tasks; use Spatie\Multitenancy\Contracts\IsTenant; interface SwitchTenantTask { public function makeCurrent(IsTenant $tenant): void; public function forgetCurrent(): void; } ``` -------------------------------- ### Migrate Tenant Databases using Laravel Multitenancy Artisan Command Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This snippet demonstrates how to run database migrations for all tenant databases using the `tenants:artisan` command provided by Laravel Multitenancy. It covers basic migration execution and specifying a dedicated path for tenant-specific migrations. ```bash php artisan tenants:artisan "migrate --database=tenant" ``` ```bash php artisan tenants:artisan "migrate --path=database/migrations/tenant --database=tenant" ``` -------------------------------- ### Execute Logic on Tenant Creation using Eloquent Callbacks Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/using-a-custom-tenant-model.md This snippet illustrates how to leverage Eloquent's `booted` method and `creating` event to perform custom logic, such as creating a database, when a new tenant model instance is being created. ```php namespace App\Models\Tenant; use Spatie\Multitenancy\Models\Tenant; class CustomTenantModel extends Tenant { protected static function booted() { static::creating(fn(CustomTenantModel $model) => $model->createDatabase()); } public function createDatabase() { // add logic to create database } } ``` -------------------------------- ### Accept Config Parameters in SwitchTenantTask Constructor (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/creating-your-own-task.md This PHP snippet shows how a `SwitchTenantTask` can accept parameters defined in the `multitenancy` config file directly through its constructor. It's crucial that the constructor parameter names match the keys provided in the configuration array for successful parameter injection. This allows tasks to be configured dynamically. ```php namespace App\Support\SwitchTenantTasks\YourTask use Spatie\Multitenancy\Tasks\SwitchTenantTask; class SwitchTenantDatabaseTask implements SwitchTenantTask { public function __construct(string $name, string $anotherName) { // do something } } ``` -------------------------------- ### Run Landlord Database Migrations Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This Bash command executes migrations specifically for the landlord database connection. It targets migration files located in 'database/migrations/landlord' and applies them to the 'landlord' database. ```bash php artisan migrate --path=database/migrations/landlord --database=landlord ``` -------------------------------- ### API Documentation for MakingTenantCurrentEvent Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/listening-for-events.md This event is fired when a tenant is in the process of being made the current tenant. At this stage, none of the environment preparation tasks have been executed yet. It provides access to the tenant instance. ```APIDOC MakingTenantCurrentEvent: description: Fired when a tenant is being made current. Tasks have not yet executed. properties: $tenant: type: Spatie\Multitenancy\Models\Tenant description: The tenant instance being made current. ``` -------------------------------- ### Register SwitchTenantTask with Parameters in Laravel Config Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/creating-your-own-task.md This configuration snippet illustrates how to register a custom `SwitchTenantTask` class within the `multitenancy` config file. It demonstrates passing key-value parameters to the task's constructor, allowing for dynamic task behavior based on application configuration. This is essential for activating custom tenant-switching logic. ```php 'switch_tenant_tasks' => [ \App\Support\SwitchTenantTasks\YourTask::class => ['name' => 'value', 'anotherName' => 'value'], // other tasks ], ``` -------------------------------- ### Configure Automatic Tenant Database Switching Task Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This PHP configuration snippet adds 'Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class' to the 'switch_tenant_tasks' array in the 'multitenancy' config file. This task ensures the database connection automatically switches to the current tenant's database. ```php /* * These tasks will be performed to make a tenant current. * * A valid task is any class that implements Spatie\Multitenancy\Tasks\SwitchTenantTask */ 'switch_tenant_tasks' => [ Spatie\\Multitenancy\\Tasks\\SwitchTenantDatabaseTask::class, ], ``` -------------------------------- ### Run External Artisan Commands Across Tenants with `tenants:artisan` Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/making-artisan-commands-tenant-aware.md Explains how to use the `tenants:artisan` command to execute any standard Artisan command (e.g., `migrate`) for all tenants, especially useful for commands from Laravel or other packages that cannot be directly modified. It also shows how to pass arguments and options, and run for specific tenants. ```bash php artisan tenants:artisan migrate ``` ```bash php artisan tenants:artisan "migrate --seed" ``` ```bash php artisan tenants:artisan "migrate --seed" --tenant=123 ``` -------------------------------- ### Configure DomainTenantFinder for Current Tenant Resolution Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/determining-current-tenant.md This PHP snippet demonstrates how to configure the `tenant_finder` key in the `multitenancy.php` configuration file. Setting it to `Spatie\Multitenancy\TenantFinder\DomainTenantFinder::class` enables the package to automatically determine the current tenant by matching the request's domain with a tenant's configured domain attribute. ```php // in multitenancy.php /* * This class is responsible for determining which tenant should be current * for the given request. * * This class should extend `Spatie\Multitenancy\TenantFinder\TenantFinder` * */ 'tenant_finder' => Spatie\Multitenancy\TenantFinder\DomainTenantFinder::class, ``` -------------------------------- ### Define Abstract Method for Custom Tenant Finder Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/automatically-determining-the-current-tenant.md This snippet shows the abstract method `findForRequest` that must be implemented by any custom tenant finder class. Custom tenant finders must extend `Spatie\Multitenancy\TenantFinder\TenantFinder` and provide their own logic within this method to determine the active tenant based on the incoming HTTP request. It should return an `IsTenant` instance or `null`. ```php abstract public function findForRequest(Request $request): ?IsTenant; ``` -------------------------------- ### Scheduling Tenant-Specific Callbacks with Laravel Scheduler (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Explains how to use the `Tenant::callback` method to define a callback that will always execute in the correct tenant context. This is particularly useful for scheduling tasks in the Laravel scheduler, allowing iteration through tenants and scheduling tenant-specific operations. ```php protected function schedule(Schedule $schedule) { Tenant::all()->eachCurrent(function(Tenant $tenant) use ($schedule) { $schedule->run($tenant->callback(fn() => cache()->flush()))->daily(); }); } ``` -------------------------------- ### Executing Tenant Code in Landlord Request to Flush Cache (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Demonstrates how to use the `execute` method on the `Tenant` model to run tenant-specific code (flushing cache) from a landlord request. The closure passed to `execute` ensures the given tenant is set as the current one. ```php Route::delete('/api/{tenant}/flush-cache', function (Tenant $tenant) { $result = $tenant->execute(fn (Tenant $tenant) => cache()->flush()); return json_encode(["success" => $result]); }); ``` -------------------------------- ### Dispatching Job from Landlord API Route for Tenant (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Illustrates another use case of `Tenant::execute` to dispatch a job within a specific tenant's context, initiated from a landlord API route. ```php Route::post('/api/{tenant}/reminder', function (Tenant $tenant) { return json_encode([ 'data' => $tenant->execute(fn () => dispatch(ExpirationReminder())), ]); }); ``` -------------------------------- ### Configure Laravel Database Connections for Multi-Tenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/installation/using-multiple-databases.md This PHP configuration defines 'tenant' and 'landlord' database connections in 'config/database.php'. The 'tenant' connection's database is dynamically set by the package, while 'landlord' points to a fixed database for system-wide data like the 'tenants' table. ```php // in config/database.php 'connections' => [ 'tenant' => [ 'driver' => 'mysql', 'database' => null, 'host' => '127.0.0.1', 'username' => 'root', 'password' => '', // And other options if needed ... ], 'landlord' => [ 'driver' => 'mysql', 'database' => 'name_of_landlord_db', 'host' => '127.0.0.1', 'username' => 'root', 'password' => '', // And other options if needed ... ], ], ``` -------------------------------- ### Iterating Tenants with eachCurrent in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/looping-over-a-collection-of-tenants.md Demonstrates how to use the `eachCurrent` method on a `TenantCollection` to iterate over all tenants. This method automatically sets the current tenant for each iteration, allowing operations to be performed in the context of that specific tenant. ```php Tenant::all()->eachCurrent(function(Tenant $tenant) { // the passed tenant has been made current Tenant::current()->is($tenant); // returns true; }); ``` -------------------------------- ### Configure SwitchTenantDatabaseTask in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/switching-databases.md This snippet shows how to register the `SwitchTenantDatabaseTask` in the `switch_tenant_tasks` array within the `config/multitenancy.php` file. This task automatically switches the `tenant` database connection to the database specified in the `Tenant` model's `database` attribute. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class, // other tasks ], ``` -------------------------------- ### Define a Tenant-Aware Artisan Command in PHP Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/making-artisan-commands-tenant-aware.md Illustrates how to create an Artisan command that is aware of the current tenant by using the `TenantAware` trait. It requires appending `{--tenant=*}` to the command signature, allowing the `handle` method to execute for each tenant or a specific one. ```php use Illuminate\Console\Command; use Spatie\Multitenancy\Commands\Concerns\TenantAware; class YourFavoriteCommand extends Command { use TenantAware; protected $signature = 'your-favorite-command {--tenant=*}'; public function handle() { return $this->line('The tenant is '. Tenant::current()->name); } } ``` -------------------------------- ### API Documentation for TenantNotFoundForRequestEvent Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/listening-for-events.md This event is fired when the `findForRequest()` method of the `TenantFinder` is unable to locate a tenant for the given incoming HTTP request. It provides access to the request instance that failed to find a tenant. ```APIDOC TenantNotFoundForRequestEvent: description: Fired when no tenant is found by the TenantFinder's findForRequest() method for the given request. properties: $request: type: Illuminate\Http\Request description: The HTTP request for which no tenant was found. ``` -------------------------------- ### Configure PrefixCacheTask for Tenant Cache Isolation Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/prefixing-cache.md This PHP snippet demonstrates how to enable the `PrefixCacheTask` in your Laravel Multitenancy application. By adding `\Spatie\Multitenancy\Tasks\PrefixCacheTask::class` to the `switch_tenant_tasks` array in `config/multitenancy.php`, you activate the task that automatically prefixes cache keys based on the current tenant, ensuring separate cache stores. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\PrefixCacheTask::class, // other tasks ], ``` -------------------------------- ### Executing Landlord Code from Tenant Request (PHP) Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/executing-code-for-tenants-and-landlords.md Shows how to execute landlord-specific code from within a tenant request using `Spatie\Multitenancy\Landlord::execute`. The closure passed to `execute` temporarily deactivates the current tenant, making the landlord active. ```php use Spatie\Multitenancy\Landlord; // ... Tenant::first()->execute(function (Tenant $tenant) { // it will clear the tenant cache Artisan::call('cache:clear'); // it will clear the landlord cache Landlord::execute(fn () => Artisan::call('cache:clear')); }); ``` -------------------------------- ### Enable Route Cache Switching Task in Laravel Multitenancy Config Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/switching-route-cache-paths.md To enable tenant-specific route cache paths, uncomment or add the `\Spatie\Multitenancy\Tasks\SwitchRouteCacheTask::class` to the `switch_tenant_tasks` array within your `config/multitenancy.php` file. This task ensures that the `APP_ROUTES_CACHE` environment variable is dynamically switched to a tenant-specific value. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\SwitchRouteCacheTask::class, // other tasks ], ``` -------------------------------- ### API Documentation for MadeTenantCurrentEvent Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/listening-for-events.md This event is fired after a tenant has successfully been made the current tenant. At this point, the `makeCurrent` method of all configured tasks has been executed, and the current tenant has been bound as 'currentTenant' in the Laravel container. ```APIDOC MadeTenantCurrentEvent: description: Fired after a tenant has been made current. All tasks' makeCurrent methods have executed, and the tenant is bound in the container. properties: $tenant: type: Spatie\Multitenancy\Models\Tenant description: The tenant instance that has been made current. ``` -------------------------------- ### Making Specific Laravel Jobs Tenant Aware Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/making-queues-tenant-aware.md To make specific jobs tenant aware when 'queues_are_tenant_aware_by_default' is 'false', jobs must implement the 'Spatie\Multitenancy\Jobs\TenantAware' interface or be listed in the 'tenant_aware_jobs' configuration array. This ensures the correct tenant context is applied during job execution. ```php use Illuminate\Contracts\Queue\ShouldQueue; use Spatie\Multitenancy\Jobs\TenantAware; class TestJob implements ShouldQueue, TenantAware { public function handle() { // do the work } } ``` ```php 'tenant_aware_jobs' => [ TestJob::class, ], ``` -------------------------------- ### Configure Custom Tenant Model in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/using-a-custom-tenant-model.md This snippet shows how to specify your custom tenant model's class name in the `multitenancy` configuration file. The custom model must extend `Spatie\Multitenancy\Models\Tenant`. ```php /* * This class is the model used for storing configuration on tenants. * * It must be or extend `Spatie\Multitenancy\Models\Tenant::class` */ 'tenant_model' => \App\Models\CustomTenantModel::class, ``` -------------------------------- ### Applying Tenant Middleware to Laravel Routes Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/ensuring-a-current-tenant-has-been-set.md This snippet shows how to apply the previously registered 'tenant' middleware group to a set of routes. By wrapping routes within `Route::middleware('tenant')->group()`, you ensure that a current tenant is active for all routes defined within that group, throwing an exception if no tenant is present. ```php // in a routes file Route::middleware('tenant')->group(function() { // routes }) ``` -------------------------------- ### Registering Tenant Middleware in Laravel Kernel Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/ensuring-a-current-tenant-has-been-set.md This snippet demonstrates how to register the `\Spatie\Multitenancy\Http\Middleware\NeedsTenant` and `\Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession` middleware in the `middlewareGroups` array within `app/Http/Kernel.php`. This ensures that a current tenant is set and its session is valid for routes using this group. ```php // in `app\Http\Kernel.php` protected $middlewareGroups = [ // ... 'tenant' => [ \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class, \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class ] ]; ``` -------------------------------- ### Manually Set Current Tenant in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/working-with-the-current-tenant.md Understand how to programmatically make a specific tenant the current one. Calling `$tenant->makeCurrent()` on a tenant instance activates it, triggering any `makeCurrent` methods of tasks configured in the `switch_tenant_tasks` array within the `multitenancy` config file. ```php $tenant->makeCurrent(); ``` -------------------------------- ### API Documentation for ForgettingCurrentTenantEvent Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/listening-for-events.md This event is fired when a tenant is in the process of being forgotten (unset as the current tenant). At this stage, none of the environment cleanup tasks have been executed yet. ```APIDOC ForgettingCurrentTenantEvent: description: Fired when a tenant is being forgotten. Tasks have not yet executed. properties: $tenant: type: Spatie\Multitenancy\Models\Tenant description: The tenant instance being forgotten. ``` -------------------------------- ### Dispatching Tenant-Aware Closures in Laravel Queues Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/making-queues-tenant-aware.md When 'queues_are_tenant_aware_by_default' is 'false', closures can be made tenant-aware by explicitly wrapping their execution within the tenant's context using '$tenant->execute()'. This ensures the closure runs with the correct tenant active, as closures cannot implement marker interfaces. ```php $tenant = Tenant::current(); dispatch(function () use ($tenant) { $tenant->execute(function () { // Your job }); }); ``` -------------------------------- ### Configure Shared Route Cache for All Tenants in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/using-tasks-to-prepare-the-environment/switching-route-cache-paths.md To enable a single route cache file shared across all tenants, set the `shared_routes_cache` option to `true` in your `config/multitenancy.php` file. This is useful when all tenants utilize the same set of routes, creating a common cache file at `bootstrap/cache/routes-v7-tenants.php`. ```php // in config/multitenancy.php 'shared_routes_cache' => true, ``` -------------------------------- ### Implement Default Domain Tenant Finder in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/automatically-determining-the-current-tenant.md This code provides the full implementation of the default `DomainTenantFinder` class. It extends `TenantFinder` and implements the `findForRequest` method, which extracts the hostname from the incoming request and queries the tenant model (specified in configuration) to find a tenant with a matching domain. This finder is responsible for automatically identifying the current tenant based on the request's domain. ```php namespace Spatie\Multitenancy\TenantFinder; use Illuminate\Http\Request; use Spatie\Multitenancy\Contracts\IsTenant; class DomainTenantFinder extends TenantFinder { public function findForRequest(Request $request): ?IsTenant { $host = $request->getHost(); return app(IsTenant::class)::whereDomain($host)->first(); } } ``` -------------------------------- ### Configure Tenant Finder in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/automatically-determining-the-current-tenant.md This snippet shows how to configure the tenant finder class in the `multitenancy.php` configuration file. By default, the `DomainTenantFinder` is used, which identifies the tenant based on the request's domain. This setting dictates which class is responsible for determining the active tenant for each incoming request. ```php // in multitenancy.php /* * This class is responsible for determining which tenant should be current * for the given request. * * This class should extend `Spatie\Multitenancy\TenantFinder\TenantFinder` * */ 'tenant_finder' => Spatie\Multitenancy\TenantFinder\DomainTenantFinder::class, ``` -------------------------------- ### Check for Active Tenant in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/working-with-the-current-tenant.md Discover how to quickly verify if a tenant is currently set as active. The `checkCurrent()` method, available on both the `Tenant` model and the `IsTenant` service container binding, returns a boolean (`true` or `false`) indicating the presence of a current tenant. ```php // Model Tenant::checkCurrent(); // returns `true` or `false` // Service Container app(IsTenant::class)::checkCurrent(); // returns `true` or `false` ``` -------------------------------- ### Access Current Tenant from Laravel Container Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/automatically-determining-the-current-tenant.md This code demonstrates how to retrieve the currently active tenant instance from the Laravel service container. After a tenant is successfully identified by the tenant finder, it is bound to the container under the `currentTenant` key, allowing easy access throughout the application. It returns the tenant object or `null` if no tenant is found. ```php app('currentTenant') // will return the current tenant or `null` ``` -------------------------------- ### Clear Specific Facade Instances on Tenant Switch in Laravel Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/using-tenant-specific-facades.md This PHP class, `ClearFacadeInstancesTask`, implements `SwitchTenantTask` to clear specific resolved facade instances when a tenant is forgotten. It's useful for scenarios where only a few facades are tenant-specific. Developers need to manually list the class names of the facades they wish to clear in the `$facadeClasses` array. ```php namespace App\Tenancy\SwitchTasks; use Illuminate\Support\Facades\Facade; use Illuminate\Support\Str; use Spatie\Multitenancy\Contracts\IsTenant; use Spatie\Multitenancy\Tasks\SwitchTenantTask; class ClearFacadeInstancesTask implements SwitchTenantTask { public function makeCurrent(IsTenant $tenant): void { // tenant is already current } public function forgetCurrent(): void { $facadeClasses = [ // array containing class names of faces you wish to clear ]; collect($facadeClasses) ->each( fn (string $facade) => $facade::clearResolvedInstance($facade::getFacadeAccessor); ); } } ``` -------------------------------- ### API Documentation for ForgotCurrentTenantEvent Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/advanced-usage/listening-for-events.md This event is fired after a tenant has been successfully forgotten. At this point, the `forgotCurrent` method of all configured tasks has been executed, and the 'currentTenant' binding in the Laravel container has been cleared. ```APIDOC ForgotCurrentTenantEvent: description: Fired after a tenant has been forgotten. All tasks' forgotCurrent methods have executed, and the currentTenant binding in the container is cleared. properties: [] ``` -------------------------------- ### Preventing Specific Laravel Jobs from Being Tenant Aware Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/making-queues-tenant-aware.md To prevent specific jobs from being tenant aware, they should implement the 'Spatie\Multitenancy\Jobs\NotTenantAware' interface or be added to the 'not_tenant_aware_jobs' configuration array. This ensures the job does not modify or rely on the current tenant context. ```php use Illuminate\Contracts\Queue\ShouldQueue; use Spatie\Multitenancy\Jobs\NotTenantAware; class TestJob implements ShouldQueue, NotTenantAware { public function handle() { // do the work } } ``` ```php 'not_tenant_aware_jobs' => [ TestJob::class, ], ``` -------------------------------- ### Clear Current Tenant in Laravel Multitenancy Source: https://github.com/spatie/laravel-multitenancy/blob/main/docs/basic-usage/working-with-the-current-tenant.md Learn how to unset or 'forget' the currently active tenant. The `forgetCurrent()` method, available on the `Tenant` model and the `IsTenant` service container binding, clears the tenant context. Subsequent calls to `Tenant::current()` will return `null`. This operation does nothing if no tenant is currently set. ```php // Model Tenant::forgetCurrent(); Tenant::current() // return null; // Service Container app(IsTenant::class)::forgetCurrent(); app(IsTenant::class)::current(); // return null ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.