### Executing Tenant-Aware Commands Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/making-artisan-commands-tenant-aware Examples of running tenant-aware commands via the CLI. ```bash php artisan your-favorite-command ``` ```bash php artisan your-favorite-command --tenant=1 ``` -------------------------------- ### Set Current Tenant in Test Setup Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Update the `setUp` method in `TestCase.php` to manually set the current tenant using `Tenant::first()->makeCurrent()`. This is necessary when performing user logins in the `setUp` method. ```php protected function setUp(): void { parent::setUp(); Event::listen(MadeTenantCurrentEvent::class, function () { $this->beginDatabaseTransaction(); }); Tenant::first()->makeCurrent(); } ``` -------------------------------- ### Implement DomainTenantFinder Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/automatically-determining-the-current-tenant Example implementation of a tenant finder that resolves the tenant based on the request host 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(); } } ``` -------------------------------- ### Install Laravel Multitenancy via Composer Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/base-installation Use this command to add the package to your Laravel project dependencies. ```bash composer require spatie/laravel-multitenancy ``` -------------------------------- ### Example PrefixCacheTask Implementation Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task A concrete implementation of SwitchTenantTask that modifies the cache prefix dynamically. ```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); } } ``` -------------------------------- ### Clear Tenant and Landlord Cache Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Execute landlord code from within a tenant request. This example first clears the tenant cache, then uses `Landlord::execute` to clear the landlord cache. ```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')); }); ``` -------------------------------- ### Registering Tasks in Configuration Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task How to register tasks and pass parameters within the multitenancy configuration file. ```php 'switch_tenant_tasks' => [ \\App\\Support\\SwitchTenantTasks\\YourTask::class => ['name' => 'value', 'anotherName' => 'value'], // other tasks ], ``` -------------------------------- ### Publish the package configuration file Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/base-installation Run this command to copy the default configuration file to your application's config directory. ```bash php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-config" ``` -------------------------------- ### Migrate All Tenant Databases Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Execute this command to loop over all tenants and run migrations for each. Ensure future migrations are stored in `database/migrations`. ```bash php artisan tenants:artisan "migrate --database=tenant" ``` -------------------------------- ### Configure the tenant finder in multitenancy.php Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/determining-current-tenant Specify the class name for the tenant finder in the multitenancy configuration file to determine the active tenant. ```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 a Custom Tenant Finder Abstract Method Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/automatically-determining-the-current-tenant Custom tenant finders must extend Spatie\Multitenancy\TenantFinder\TenantFinder and implement this abstract method to return an IsTenant instance. ```php abstract public function findForRequest(Request $request): ?IsTenant; ``` -------------------------------- ### Define Tenant and Landlord Database Connections Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Configure 'tenant' and 'landlord' database connections in `config/database.php`. For the 'tenant' connection, set `database` to `null` as the package will manage it dynamically. The 'landlord' connection requires a specific database name. ```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 ... ], ], ``` -------------------------------- ### Implementing TenantAware Command Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/making-artisan-commands-tenant-aware Apply the TenantAware trait to a command and include the tenant option in the signature to enable multi-tenant execution. ```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); } } ``` -------------------------------- ### Configure SwitchTenantDatabaseTask Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-databases Register the task in the multitenancy configuration file to enable automatic database switching. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\SwitchTenantDatabaseTask::class, // other tasks ], ``` -------------------------------- ### Migrate the landlord database Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-a-single-database Publishes the package migrations and executes the migration command for the landlord database to create the tenants table. ```bash php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-migrations" php artisan migrate --path=database/migrations/landlord ``` -------------------------------- ### Execute Logic on Tenant Creation Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-a-custom-tenant-model Use Eloquent's booted lifecycle callback to trigger custom logic when a tenant is 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 } } ``` -------------------------------- ### Configure Tenant Switching Task Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Add the `SwitchTenantDatabaseTask` to the `switch_tenant_tasks` array in the `multitenancy` config file. This task ensures the tenant database connection is correctly set for each request. ```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, ], ``` -------------------------------- ### Demonstrate Tenant-Specific Cache Behavior Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/prefixing-cache Illustrates how cache keys behave differently across tenants when PrefixCacheTask is enabled. Cache entries are isolated per tenant. ```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' ``` -------------------------------- ### Schedule Tenant Cache Flush with Callback Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Schedule a callback to flush a tenant's cache daily using `Tenant::callback` and `Tenant::all()->eachCurrent`. This ensures the cache is flushed within the correct tenant context. ```php protected function schedule(Schedule $schedule) { Tenant::all()->eachCurrent(function(Tenant $tenant) use ($schedule) { $schedule->run($tenant->callback(fn() => cache()->flush()))->daily(); }); } ``` -------------------------------- ### Publish Tenant Migrations Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Publish the migration file for the landlord database using the provided Artisan command. This will create a migration in the `database/migrations/landlord` directory. ```bash php artisan vendor:publish --provider="Spatie\Multitenancy\MultitenancyServiceProvider" --tag="multitenancy-migrations" ``` -------------------------------- ### Migrate Landlord Database Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Run the landlord database migration using the specified path and database connection. Ensure the `--database` option matches your configured landlord connection name. ```bash php artisan migrate --path=database/migrations/landlord --database=landlord ``` -------------------------------- ### Registering tenant middleware in Kernel Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/ensuring-a-current-tenant-has-been-set Add the middleware to your middleware groups in app/Http/Kernel.php to enforce tenant requirements. ```php // in `app\Http\Kernel.php` protected $middlewareGroups = [ // ... 'tenant' => [ \Spatie\Multitenancy\Http\Middleware\NeedsTenant::class, \Spatie\Multitenancy\Http\Middleware\EnsureValidTenantSession::class ] ]; ``` -------------------------------- ### Migrate Tenant Databases with Custom Path Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Use this command when tenant-specific migrations are located in a dedicated directory like `database/migrations/tenant`. ```bash php artisan tenants:artisan "migrate --path=database/migrations/tenant --database=tenant" ``` -------------------------------- ### Seed Tenant Databases Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Run this command to execute all seeders for tenant databases. Use `Tenant::checkCurrent()` in your `DatabaseSeeder` to differentiate between tenant and landlord seeding. ```bash php artisan tenants:artisan "migrate --database=tenant --seed" ``` -------------------------------- ### Using tenants:artisan Command Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/making-artisan-commands-tenant-aware Execute standard Artisan commands across all tenants or specific ones. ```bash php artisan tenants:artisan migrate ``` ```bash php artisan tenants:artisan "migrate --seed" ``` ```bash php artisan tenants:artisan "migrate --seed" --tenant=123 ``` -------------------------------- ### Enable Tenant-Specific Route Cache Task Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths Uncomment the `SwitchRouteCacheTask` in the `multitenancy` configuration file to enable tenant-specific route caching. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\SwitchRouteCacheTask::class, // other tasks ], ``` -------------------------------- ### Clear facade instances task Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-tenant-specific-facades Implements a SwitchTenantTask to clear specific facade instances during tenant switching. Add the desired facade class names to 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); ); } } ``` -------------------------------- ### Accepting Parameters in Task Constructor Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task Tasks receive configuration parameters via their constructor based on matching argument names. ```php namespace App\\Support\\SwitchTenantTasks\\YourTask use Spatie\\Multitenancy\\Tasks\\SwitchTenantTask; class SwitchTenantDatabaseTask implements SwitchTenantTask { public function __construct(string $name, string $anotherName) { // do something } } ``` -------------------------------- ### Implement IsTenant Interface Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-a-custom-tenant-model Use the IsTenant interface and ImplementsTenant trait to make an existing model act as a tenant. ```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; } ``` -------------------------------- ### Configure Custom Tenant Model Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-a-custom-tenant-model Specify the custom model class in the multitenancy configuration file. ```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, ``` -------------------------------- ### Cache Routes for Each Tenant Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths Use the `php artisan tenant:artisan route:cache` command to generate a separate route cache file for each tenant. This is crucial when tenants have distinct routes. ```bash php artisan tenant:artisan route:cache ``` -------------------------------- ### Iterate and Set Current Tenant Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/looping-over-a-collection-of-tenants Use `eachCurrent` to loop through tenants, automatically setting each as the current tenant within the closure. This is useful for performing actions on each tenant. ```php Tenant::all()->eachCurrent(function(Tenant $tenant) { // the passed tenant has been made current Tenant::current()->is($tenant); // returns true; }); ``` -------------------------------- ### Implement ClearFacadeInstancesTask for Tenant Switching Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/using-tenant-specific-facades Use this task to clear resolved facade instances in the App namespace during the tenant forget process. It implements the SwitchTenantTask interface. ```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() )); } } ``` -------------------------------- ### Manually set the current tenant Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Sets the tenant as the current one and executes all tasks defined in the multitenancy configuration. ```php $tenant->makeCurrent(); ``` -------------------------------- ### Tenant-Aware Database Seeder Logic Source: https://spatie.be/docs/laravel-multitenancy/v4/installation/using-multiple-databases Implement this logic in your `DatabaseSeeder` to conditionally run seeders based on whether the current context is a tenant or the landlord. Requires `spatie/laravel-multitenancy`. ```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 NotTenantAware interface for jobs Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/making-queues-tenant-aware Use the NotTenantAware interface to ensure a job does not interact with 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, ], ``` -------------------------------- ### Update Package Version Source: https://spatie.be/docs/laravel-multitenancy/v4/upgrade-guide Run this command to upgrade to the latest v4 version of the package. ```bash composer require spatie/laravel-multitenancy:^4.0 ``` -------------------------------- ### Dispatch Job for Tenant via Landlord Request Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Dispatch a job for a specific tenant from a landlord API route using `Tenant::execute`. The closure is executed within the tenant's context. ```php Route::post('/api/{tenant}/reminder', function (Tenant $tenant) { return json_encode([ 'data' => $tenant->execute(fn () => dispatch(ExpirationReminder())), ]); }); ``` -------------------------------- ### Dispatch tenant-aware closures Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/making-queues-tenant-aware Manually execute code within a tenant context when dispatching closures to the queue. ```php $tenant = Tenant::current(); dispatch(function () use ($tenant) { $tenant->execute(function () { // Your job }); }); ``` -------------------------------- ### Configure Database Transactions for Tenant Testing Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Configure the `TestCase.php` to use `DatabaseTransactions` on both landlord and tenant connections. This ensures database transactions are correctly managed during testing. ```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(); }); } } ``` -------------------------------- ### Configure PrefixCacheTask in multitenancy.php Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/prefixing-cache Add the PrefixCacheTask to the 'switch_tenant_tasks' array in your multitenancy configuration file to enable tenant-specific cache prefixes. ```php // in config/multitenancy.php 'switch_tenant_tasks' => [ \Spatie\Multitenancy\Tasks\PrefixCacheTask::class, // other tasks ], ``` -------------------------------- ### Find Current Tenant using Tenant Model Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Retrieve the current tenant using the `Tenant::current()` method. Returns `null` if no tenant is set. ```php Tenant::current(); // returns the current tenant, or if no tenant is current, `null` ``` -------------------------------- ### Applying tenant middleware to routes Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/ensuring-a-current-tenant-has-been-set Use the registered middleware group in your route files to protect specific routes. ```php // in a routes file Route::middleware('tenant')->group(function() { // routes }) ``` -------------------------------- ### Access Current Tenant via Container Key Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant The current tenant is also bound in the container under the key 'currentTenant'. Access it using `app('currentTenant')`. Returns `null` if no tenant is set. ```php app('currentTenant'); // returns the current tenant, or if no tenant is current, `null` ``` -------------------------------- ### Implement TenantAware interface for jobs Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/making-queues-tenant-aware Use the TenantAware interface to explicitly mark a job as tenant-aware when global queue awareness is disabled. ```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, ], ``` -------------------------------- ### Access Current Tenant Instance Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/automatically-determining-the-current-tenant After a tenant is identified and its tasks are performed, the tenant instance is bound to the container. You can retrieve the current tenant using the `currentTenant` key. ```php app('currentTenant') // will return the current tenant or `null` ``` -------------------------------- ### Find Current Tenant using Service Container Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Retrieve the current tenant via the service container using `app(IsTenant::class)::current()`. Returns `null` if no tenant is set. ```php app(IsTenant::class)::current(); // returns the current tenant, or if no tenant is current, `null` ``` -------------------------------- ### Custom Tenant Finder Adjustment Source: https://spatie.be/docs/laravel-multitenancy/v4/upgrade-guide When using a custom tenant finder, ensure the `findForRequest` method returns `?IsTenant` instead of `Tenant`. ```php use Illuminate\Http\Request; use Spatie\Multitenancy\Contracts\IsTenant; class YourCustomTenantFinder extends TenantFinder { public function findForRequest(Request $request): ?IsTenant { // ... } } ``` -------------------------------- ### MakingTenantCurrentEvent Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events This event is fired when a tenant is about to be made the current one. At this stage, no tasks have been executed yet. The event contains a public property `$tenant` which holds the `Spatie\Multitenancy\Models\Tenant` instance. ```APIDOC ## `MakingTenantCurrentEvent` ### Description This event fires just before a tenant is set as the current tenant. No preparatory tasks have been executed at this point. ### Event Class `\Spatie\Multitenancy\Events\MakingTenantCurrentEvent` ### Properties - **$tenant** (`Spatie\Multitenancy\Models\Tenant`) - The tenant instance that is about to become current. ``` -------------------------------- ### Enable Shared Route Cache Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths Set `shared_routes_cache` to `true` in the `multitenancy` configuration file to use a single route cache file for all tenants. This is suitable when all tenants share the same routes. ```php // in config/multitenancy.php 'shared_routes_cache' => true, ``` -------------------------------- ### Managing State in TenantAware Commands Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/making-artisan-commands-tenant-aware Reset instance properties within the handle method to prevent state leakage between tenant executions. ```php use Illuminate\Console\Command; use Spatie\Multitenancy\Commands\Concerns\TenantAware; class YourFavoriteCommand extends Command { use TenantAware; protected $signature = 'your-favorite-command {--tenant=*}'; protected int $counter = 0; public function handle() { // Reset state at the beginning of each tenant execution $this->counter = 0; // Without the reset above, $counter would start at the value // from the previous tenant's execution $this->incrementCounter(); return $this->line('Counter: '. $this->counter); } public function incrementCounter() { $this->counter++; } } ``` -------------------------------- ### SwitchTenantTask Interface Definition Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task The base interface that all tenant switching tasks must implement. ```php namespace Spatie\\\Multitenancy\\\Tasks; use Spatie\\\Multitenancy\\\Contracts\\\IsTenant; interface SwitchTenantTask { public function makeCurrent(IsTenant $tenant): void; public function forgetCurrent(): void; } ``` -------------------------------- ### Injecting Dependencies in Task Constructor Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/creating-your-own-task Constructors can also be used for dependency injection alongside configuration parameters. ```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 } } ``` -------------------------------- ### Flush Tenant Cache via Landlord Request Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/executing-code-for-tenants-and-landlords Use the `Tenant::execute` method to flush a specific tenant's cache from a landlord API route. The closure receives the current tenant as an argument. ```php Route::delete('/api/{tenant}/flush-cache', function (Tenant $tenant) { $result = $tenant->execute(fn (Tenant $tenant) => cache()->flush()); return json_encode(["success" => $result]); }); ``` -------------------------------- ### Check if a Current Tenant is Set using Tenant Model Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Verify if a tenant is currently set using the `Tenant::checkCurrent()` method. Returns a boolean. ```php Tenant::checkCurrent(); // returns `true` or `false` ``` -------------------------------- ### Cache Routes with Shared Cache Source: https://spatie.be/docs/laravel-multitenancy/v4/using-tasks-to-prepare-the-environment/switching-route-cache-paths When using a shared route cache, employ `php artisan tenant:artisan route:cache --tenant=YOUR-TENANT-ID` to cache routes. This ensures a single cache file is generated for all tenants. ```bash php artisan tenant:artisan route:cache --tenant=YOUR-TENANT-ID ``` -------------------------------- ### Check if a Current Tenant is Set using Service Container Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Verify if a tenant is currently set via the service container using `app(IsTenant::class)::checkCurrent()`. Returns a boolean. ```php app(IsTenant::class)::checkCurrent(); // returns `true` or `false` ``` -------------------------------- ### Forget the current tenant Source: https://spatie.be/docs/laravel-multitenancy/v4/basic-usage/working-with-the-current-tenant Clears the current tenant context from both the model and the service container. ```php // Model Tenant::forgetCurrent(); Tenant::current() // return null; // Service Container app(IsTenant::class)::forgetCurrent(); app(IsTenant::class)::current(); // return null ``` -------------------------------- ### TenantNotFoundForRequestEvent Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events Fired when the TenantFinder cannot locate a tenant for the current request. ```APIDOC ## TenantNotFoundForRequestEvent ### Description This event will fire when no tenant was found by the `findForRequest()` method of the `TenantFinder` for the given request. ### Public Properties - **$request** (Illuminate\Http\Request) - The incoming request instance for which no tenant was found. ``` -------------------------------- ### MadeTenantCurrentEvent Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events This event is fired after a tenant has been successfully made the current one. All tasks associated with making the tenant current have been executed, and the tenant is bound to the container as `currentTenant`. The event also contains the `$tenant` property. ```APIDOC ## `MadeTenantCurrentEvent` ### Description This event fires after a tenant has been successfully set as the current tenant. All associated tasks have been completed, and the tenant is registered in the container. ### Event Class `\Spatie\Multitenancy\Events\MadeTenantCurrentEvent` ### Properties - **$tenant** (`Spatie\Multitenancy\Models\Tenant`) - The tenant instance that has become current. ``` -------------------------------- ### ForgotCurrentTenantEvent Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events Fired after a tenant has been successfully forgotten. All relevant tasks have been executed, and the current tenant is cleared. ```APIDOC ## ForgotCurrentTenantEvent ### Description This event will fire when a tenant has been forgotten. At this point the `forgotCurrent` method of all of the tasks have been executed. `currentTenant` in the container has been emptied. ### Public Properties - **$tenant** (Spatie\Multitenancy\Models\Tenant) - An instance of the tenant that was just forgotten. ``` -------------------------------- ### ForgettingCurrentTenantEvent Source: https://spatie.be/docs/laravel-multitenancy/v4/advanced-usage/listening-for-events Fired when a tenant is about to be forgotten. No tasks have been executed at this stage. ```APIDOC ## ForgettingCurrentTenantEvent ### Description This event will fire when a tenant is being forgotten. At this point none of the tasks have been executed. ### Public Properties - **$tenant** (Spatie\Multitenancy\Models\Tenant) - An instance of the tenant being forgotten. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.