### Install Allotment using Laravel Installer Source: https://github.com/sprout-laravel/docs/blob/1.x/starter-kit.md This command installs the Sprout Allotment starter kit for a new Laravel project using the Laravel installer. It requires the Laravel installer to be globally available. ```bash laravel new my-project --using=sprout/allotment ``` -------------------------------- ### Install Allotment using Composer Source: https://github.com/sprout-laravel/docs/blob/1.x/starter-kit.md This command installs the Sprout Allotment starter kit for a new project using Composer. It creates a new project directory named 'my-project' and populates it with the Allotment starter kit. ```bash composer create-project sprout/allotment my-project ``` -------------------------------- ### Define Eloquent Tenant Model Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md Defines a custom Eloquent model (`Blog` in this example) that implements the `Tenant` interface and uses the `IsTenant` trait from Sprout. This model represents a tenant in your multitenant application. ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Sprout\Contracts\Tenant; use Sprout\Database\Eloquent\Concerns\IsTenant; class Blog extends Model implements Tenant { use IsTenant; } ``` -------------------------------- ### Install Sprout via Composer Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md Installs the Sprout package into your Laravel application using Composer. This is the first step in setting up multitenancy. ```shell composer require sprout/sprout ``` -------------------------------- ### Publish Sprout Configuration Files Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md Publishes Sprout's configuration files to your Laravel application's `config` directory using the `vendor:publish` Artisan command. This makes Sprout's settings customizable. ```shell php artisan vendor:publish --provider="Sprout\SproutServiceProvider" ``` -------------------------------- ### Define Tenant Child Model (Post) Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md This example shows how to define a tenant child model, 'Post', that belongs to a 'Blog' tenant. It utilizes the `BelongsToTenant` trait and the `TenantRelation` attribute to automatically scope and associate posts with the current tenant. ```php namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Sprout\Attributes\TenantRelation; use Sprout\Database\Eloquent\Concerns\BelongsToTenant; class Post extends Model { use BelongsToTenant; // [tl! ++] #[TenantRelation] // [tl! ++] public function blog(): BelongsTo { return $this->belongsTo(Blog::class); } } ``` -------------------------------- ### Define Tenant-Scoped Filesystem Disk (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Example configuration for creating a tenant-scoped filesystem disk using the 'sprout' driver. This allows disks to be isolated per tenant, based on an existing disk configuration. ```php 'tenant-disk' => [ 'driver' => 'sprout', 'disk' => 'local', ], ``` -------------------------------- ### Full Subdomain Identity Resolver Configuration (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This comprehensive configuration example for the subdomain identity resolver includes driver, domain, custom parameter naming, and a regular expression pattern. It illustrates how to fully customize tenant identification for subdomain-based multitenancy. ```php 'subdomain' => [ 'driver' => 'subdomain', 'domain' => env('TENANTED_DOMAIN'), 'parameter' => '{tenancy}_{resolver}', 'pattern' => '.*' ] ``` -------------------------------- ### Define Tenant-Aware Cache Store (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Example configuration for a tenant-aware cache store using the 'sprout' driver. The 'override' key specifies the base cache store to be prefixed with tenant information. ```php 'tenant-store' => [ 'driver' => 'sprout', 'override' => 'file', ], ``` -------------------------------- ### Register Tenant Routes with Sprout Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md This snippet demonstrates how to register routes that should be specific to a tenant using Sprout's `Route::tenanted` macro. Ensure the `TENANTED_DOMAIN` environment variable is set for subdomain-based tenant resolution. ```env TENANTED_DOMAIN=localhost ``` ```php Route::tenanted(function () { Route::get('/', function () { return view('welcome'); }); }) ``` -------------------------------- ### Manually Register Sprout Service Provider Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md Manually registers the Sprout service provider in `bootstrap/providers.php` if auto-discovery is disabled or for manual control. This ensures Sprout's services are available to your application. ```php return [ Sprout\SproutServiceProvider::class, App\Providers\AppServiceProvider::class, ]; ``` -------------------------------- ### Customize Tenant-Scoped Filesystem Disk Path (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Example showing how to customize the path for a tenant-scoped filesystem disk. The 'path' option uses placeholders for tenancy and tenant resource keys, allowing flexible storage organization. ```php 'tenant-disk' => [ 'driver' => 'sprout', 'disk' => 'local', 'path' => '/{tenancy}/files/{tenant}' ], ``` -------------------------------- ### Configure Tenant Model in Sprout Config Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md Updates the `config/multitenancy.php` file to specify the custom tenant model (`App\Models\Blog::class`) to be used by Sprout's Eloquent tenant provider. This directs Sprout to use your defined tenant model. ```php 'providers' => [ 'tenants' => [ 'driver' => 'eloquent', 'model' => \App\Models\Blog::class ], ], ``` -------------------------------- ### Add Tenant Columns to Session Table Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This SQL schema modification adds 'tenancy' and 'tenant_id' columns to the 'sessions' table, supporting Sprout's tenant-aware database session handling. This is necessary if you are using the database driver for sessions and haven't followed the initial installation guide for overrides. ```sql Schema::create('sessions', function (Blueprint $table) { $table->string('id')->primary(); $table->string('tenancy')->nullable();// [tl! ++] $table->unsignedBigInteger('tenant_id')->nullable();// [tl! ++] $table->foreignId('user_id')->nullable()->index(); $table->string('ip_address', 45)->nullable(); $table->text('user_agent')->nullable(); $table->longText('payload'); $table->integer('last_activity')->index(); }); ``` -------------------------------- ### Temporarily Ignore Tenant Restrictions Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md These PHP code examples show how to temporarily bypass tenant restrictions for Eloquent models. The first example uses `ignoreTenantRestrictions()` and `resetTenantRestrictions()` methods, while the second uses the `withoutTenantRestrictions()` callback for a more contained approach. ```php Post::ignoreTenantRestrictions(); $posts = Post::all(); Post::resetTenantRestrictions(); ``` ```php $posts = Post::withoutTenantRestrictions(function () { return Post::all(); }); ``` -------------------------------- ### Get Current Tenant with Contextual Attribute (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Demonstrates how to retrieve the current tenant model within a multi-tenanted context using Laravel's contextual attributes. This requires the `Sprout\Attributes\CurrentTenant` attribute. ```php public function __construct(#[CurrentTenant] Blog $blog) { $this->blog = $blog; } ``` -------------------------------- ### Modify Sessions Table for Tenancy Source: https://github.com/sprout-laravel/docs/blob/1.x/installation.md This code adds `tenancy` and `tenant_id` columns to the Laravel sessions table to support tenant-specific sessions. This is necessary when using Sprout's session override with the database driver. ```php $table->string('tenancy')->nullable(); $table->unsignedBigInteger('tenant_id')->nullable(); ``` -------------------------------- ### Define Tenant Child Model with BelongsToTenant Trait Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md This PHP code demonstrates how to define a tenant child model using the `BelongsToTenant` trait and the `TenantRelation` attribute. This setup automatically scopes read queries and associates new models with the current tenant when within a multitenanted context. ```php use Sprout\Attributes\TenantRelation; use Sprout\Database\Eloquent\Concern\BelongsToTenant; class Post extends Model { use BelongsToTenant; #[TenantRelation] public function blog(): BelongsTo { return $this->belongsTo(Blog::class); } } ``` -------------------------------- ### Define Tenant-Scoped Filesystem Disk with New Settings (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration demonstrates creating a tenant-scoped filesystem disk with custom settings. It defines the driver as 'sprout' and provides new disk configurations, such as root path and throw options. ```php 'tenant-disk' => [ 'driver' => 'sprout', 'disk' => [ 'driver' => 'local', 'root' => storage_path('tenants'), 'throw' => false, ], ], ``` -------------------------------- ### Configure Tenant Providers in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md Defines tenant providers for your Sprout Laravel application. This section specifies the driver and model for retrieving tenant instances. The 'eloquent' driver is the default and requires a 'model' option. ```php "providers" => [ "tenants" => [ "driver" => "eloquent", "model" => \Sprout\Database\Eloquent\Tenant::class, ], ], ``` -------------------------------- ### Configure Sprout Middleware Priority in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This PHP snippet demonstrates how to configure the middleware priority in Laravel's `bootstrap/app.php` file. It specifically shows how to append the `SproutTenantContextMiddleware` to come after the `StartSession` middleware, ensuring proper tenant context is established. ```php return Application::configure(basePath: dirname(__DIR__)) ->withMiddleware(function (Middleware $middleware) { $middleware->appendToPriorityList( Illuminate\Session\Middleware\StartSession::class, Sprout\Http\Middleware\SproutTenantContextMiddleware::class ); }); ``` -------------------------------- ### Eloquent Tenant Provider Configuration (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md This configuration snippet shows how to set up the Eloquent tenant provider in Sprout. It specifies the driver as 'eloquent' and defines the Eloquent model class to be used for tenant management. ```php 'providers' => [ 'tenants' => [ 'driver' => 'eloquent', 'model' => \App\Models\Blog::class, ], ], ``` -------------------------------- ### Configure Identity Resolvers in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md Sets up various identity resolvers for Sprout Laravel to identify tenants. Supports drivers like 'subdomain', 'header', 'path', 'cookie', and 'session', each with specific configuration options. ```php "resolvers" => [ "subdomain" => [ "driver" => "subdomain", "domain" => env('TENANTED_DOMAIN'), "pattern" => '.*', ], "header" => [ "driver" => "header", "header" => '{Tenancy}-Identifier', ], "path" => [ "driver" => "path", "segment" => 1, ], "cookie" => [ "driver" => "cookie", "cookie" => '{Tenancy}-Identifier', ], "session" => [ "driver" => "session", "session" => 'multitenancy.{tenancy}', ], ], ``` -------------------------------- ### Define Tenant Routes using Router Macro - PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This code snippet demonstrates how to define tenant routes using the `Route::tenanted` macro in Sprout Laravel. It shows various configurations including default settings, manual resolver, manual tenancy, and both manual resolver and tenancy. This is the preferred method for defining tenant routes as it supports route parameters for certain resolvers. ```php [ 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::hydrateTenantRelation(), TenancyOptions::throwIfNotRelated(), TenancyOptions::allOverrides(), ], ], ], ``` -------------------------------- ### Configure Resolution Hooks in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md Defines Sprout Laravel's core resolution hooks in the `config/sprout/core.php` file. These hooks determine when Sprout interacts with the Laravel lifecycle to identify a tenant. Options include Routing and Middleware. ```php 'hooks' => [ // \Sprout\Support\ResolutionHook::Booting, \Sprout\Support\ResolutionHook::Routing, \Sprout\Support\ResolutionHook::Middleware, ], ``` -------------------------------- ### Sprout URL Generation Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This section explains how to generate URLs for named tenant routes using the Sprout facade or helper method, especially when outside the current tenant context. ```APIDOC ## Sprout URL Generation ### Description Generates URLs for named tenant routes, providing flexibility when not within a current tenant context or for routes with different identity providers. ### Method `Sprout::route()` or `sprout()->route()` ### Endpoint N/A (Facade/Helper method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```php // Using Sprout Facade Sprout\Facades\Sprout::route('my.route.name', $tenant); // Using sprout() helper method sprout()->route('my.route.name', $tenant); ``` ### Response #### Success Response (200) Returns a URL string for the specified named route and tenant. #### Response Example ```json { "url": "https://your-tenant-domain.com/path/to/route" } ``` ### Available Arguments (for `Sprout::route()` and `sprout()->route()`) - `name` (string) - Required - The name of the route. - `tenant` (Sprout\Contracts\Tenant) - Required - The tenant instance. - `resolver` (string|null) - Optional - The registered name of the resolver to use. Defaults to null. - `tenancy` (string|null) - Optional - The registered name of the tenancy to use. Defaults to null. - `parameters` (array) - Optional - Parameters for the URL, excluding tenant parameters. - `absolute` (bool) - Optional - Whether to generate an absolute URL. Defaults to true. ``` -------------------------------- ### Configure Tenancy Bootstrappers in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md This PHP code configures the tenancy bootstrappers for Sprout Laravel. These classes are responsible for bootstrapping a tenancy once a tenant becomes active. They are registered as listeners for the CurrentTenantChanged event. ```php 'bootstrappers' => [ // Set the current tenant within the Laravel context \Sprout\Listeners\SetCurrentTenantContext::class, // Calls the setup method on the current identity resolver \Sprout\Listeners\PerformIdentityResolverSetup::class, // Performs any clean-up from the previous tenancy \Sprout\Listeners\CleanupServiceOverrides::class, // Sets up service overrides for the current tenancy \Sprout\Listeners\SetupServiceOverrides::class, // Refresh anything that's tenant-aware \Sprout\Listeners\RefreshTenantAwareDependencies::class, ] ``` -------------------------------- ### Parameter-based Identity Resolvers Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md Explains parameter-based identity resolvers, which leverage Laravel's route parameter functionality for tenant identification. ```APIDOC ## Parameter-based Identity Resolvers ### Description Parameter-based identity resolvers utilize Laravel's route parameter functionality to identify tenants. They can handle routes without explicit tenant parameters and configure automatic routes accordingly. ### Key Features - **Route Parameter Integration**: Can use route parameters for tenant identification. - **Parameter Naming and Pattern Control**: Allow configuration of parameter names and matching patterns for first-party Sprout resolvers. ``` -------------------------------- ### Stacking Service Overrides in Laravel Config Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Demonstrates how to configure multiple service overrides for a single service using Sprout's StackedOverride. This is useful when a service's override is modular or when integrating overrides from different sources. The configuration specifies the StackedOverride class and lists the individual drivers to be stacked. ```php 'filesystem' => [ 'driver' => \Sprout\Overrides\StackedOverride::class, 'overrides' => [ \Sprout\Overrides\FilesystemManagerOverride::class, \Sprout\Overrides\FilesystemOverride::class, ], ], ``` -------------------------------- ### Enabling All Service Overrides for Tenancy in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Shows how to configure tenancy options in Laravel to enable all available service overrides by default. This is typically set within the `tenants.options` configuration, utilizing the `TenancyOptions::allOverrides()` helper method. ```php 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::allOverrides(), ], ], ``` -------------------------------- ### Define Tenant Routes using Middleware - PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This code snippet illustrates how to manually specify routes as tenanted using the `sprout.tenanted` middleware in Sprout Laravel. It shows different ways to apply the middleware with parameters for resolver and tenancy, including default tenancy, manual resolver, default resolver with manual tenancy, and both manual resolver and tenancy. This method can have side effects, especially with resolvers that utilize route parameters. ```php get('/', ''); // Default tenancy, manual resolver Route::middleware(['sprout.tenanted:subdomain'])->get('/', ''); // Default resolver, manual tenancy Route::middleware(['sprout.tenanted:,tenants'])->get('/', ''); // Manual resolver, manual tenancy Route::middleware(['sprout.tenanted:subdomain,tenants'])->get('/', ''); ``` -------------------------------- ### Retrieve Current Tenancy in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Shows three common methods for accessing the current tenancy instance within a Laravel application: dependency injection using a contextual attribute, calling a facade, and using a helper function. These methods abstract the retrieval of the tenancy information. ```php // Using dependency injection public function __construct(#[CurrentTenancy] Tenancy $tenancy) {} // Using facades Sprout::getCurrentTenancy() // Using helper methods sprout()->getCurrentTenancy(); ``` -------------------------------- ### Configure Multitenancy Defaults in Sprout Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md Sets the default tenancy, provider, and resolver for Sprout within a Laravel application. This configuration is crucial for defining how multitenancy is handled when not explicitly specified. ```php 'defaults' => [ 'tenancy' => 'tenants', 'provider' => 'tenants', 'resolver' => 'subdomain', ], ``` -------------------------------- ### Configure Session Identity Resolver in PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This configuration snippet shows how to set up the session driver for tenant identification in Sprout Laravel. It sets the driver to 'session' and allows customization of the session key using the 'session' option, which supports dot notation. The default session key is 'multitenancy.{tenancy}'. ```php 'session' => [ 'driver' => 'session', 'session' => 'multitenancy.{tenancy}' ] ``` -------------------------------- ### Configure Service Overrides in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/configuration.md This PHP code defines the service overrides configuration for Sprout Laravel. Service overrides are used to make specific services multitenanted, including components of Laravel and other packages like Livewire or Filament. The configuration lists the drivers and specific overrides for various services. ```php return [ 'filesystem' => [ 'driver' => \Sprout\Overrides\StackedOverride::class, 'overrides' => [ \Sprout\Overrides\FilesystemManagerOverride::class, \Sprout\Overrides\FilesystemOverride::class, ], ], 'job' => [ 'driver' => \Sprout\Overrides\JobOverride::class, ], 'cache' => [ 'driver' => \Sprout\Overrides\CacheOverride::class, ], 'auth' => [ 'driver' => \Sprout\Overrides\StackedOverride::class, 'overrides' => [ \Sprout\Overrides\AuthGuardOverride::class, \Sprout\Overrides\AuthPasswordOverride::class, ], ], 'cookie' => [ 'driver' => \Sprout\Overrides\CookieOverride::class, ], 'session' => [ 'driver' => \Sprout\Overrides\SessionOverride::class, 'database' => false, ], ]; ``` -------------------------------- ### Configure Database Tenant Provider Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md This PHP code snippet shows how to configure the database tenant provider in Laravel's configuration. It specifies the driver, the tenant table name, the tenant entity class, and the database connection to use for managing tenants. ```php 'providers' => [ 'tenants' => [ 'driver' => 'database', 'table' => 'blogs', 'entity' => BlogEntity::class, 'connection' => 'core', ], ], ``` -------------------------------- ### Generate Tenant URL with Sprout Facade or Helper (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md Generates a URL for a named route associated with a specific tenant. This method is useful when generating URLs outside of the current tenant's context. It accepts the route name, tenant object, and optional parameters for resolver, tenancy, route parameters, and absolute URL generation. Dependencies include the Sprout facade or helper function. ```php Sprout\Facades\Sprout::route('my.route.name', $tenant); sprout()->route('my.route.name', $tenant); ``` -------------------------------- ### Configure Path Identity Resolver in PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This configuration sets up the path driver for tenant identification in Sprout Laravel. It includes options for the driver ('path'), the segment number where the tenant identifier is located ('segment'), a parameter pattern ('parameter'), and a regex pattern ('pattern'). ```php 'path' => [ 'driver' => 'path', 'segment' => 1, 'parameter' => '{tenancy}_{resolver}', 'pattern' => '.*' ], ``` -------------------------------- ### Enabling Specific Service Overrides for Tenancy in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md Illustrates how to configure tenancy options to enable only a specific list of service overrides. This provides granular control over which overrides are active for a given tenancy, using the `TenancyOptions::overrides()` method with an array of service names. ```php 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::overrides([ 'job', 'filesystem', 'cache' ]), ], ], ``` -------------------------------- ### Tenant Model Interfaces for Resources (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md These methods define the contract for tenant models that need to manage resources within Sprout. They specify how to retrieve the tenant's resource key and its corresponding attribute name. ```php public function getTenantResourceKey(): string; public function getTenantResourceKeyName(): string; ``` -------------------------------- ### Configure Sprout Cache Override (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration sets up the Sprout Cache override, which prefixes cache keys with the tenancy name and tenant key. It requires a cache store configuration with the 'sprout' driver. ```php 'cache' => [ 'driver' => \Sprout\Overrides\CacheOverride::class, ], ``` -------------------------------- ### Configure Cookie Identity Resolver in PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This PHP configuration demonstrates how to set up the cookie driver for tenant identification in Sprout Laravel. It specifies the driver as 'cookie', allows custom cookie names via the 'cookie' option, and provides an 'options' array for setting cookie attributes like 'minutes', 'path', 'domain', 'secure', 'http_only', and 'same_site'. ```php 'cookie' => [ 'driver' => 'cookie', 'cookie' => '{Tenancy}-Identifier', 'options' => [ 'minutes' => 43800, 'path' => '/tenants/', 'domain' => 'localhost', 'secure' => false, 'http_only' => true, 'same_site' => 'lax' ], ], ``` -------------------------------- ### Configure Session Service Override in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration replaces Laravel's default session drivers ('file', 'native', 'domain') with Sprout's tenant-aware versions. It prefixes paths for 'file'/'native' drivers and populates 'tenancy' and 'tenant_id' for the 'database' driver. ```php 'session' => [ 'driver' => \Sprout\Overrides\SessionOverride::class, 'database' => false, ], ``` -------------------------------- ### Specify Service Overrides (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Allows Sprout to use specific service overrides for tenancy. You provide an array of override names registered in the sprout.core.overrides configuration. ```php 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::hydrateTenantRelation(), TenancyOptions::throwIfNotRelated(), TenancyOptions::overrides([ 'job', 'filesystem', 'cache' ]), ], ], ``` -------------------------------- ### Resolution Hooks Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md Details on Sprout's resolution hooks, which control where tenant identification occurs within a request's lifecycle. ```APIDOC ## Resolution Hooks ### Description Sprout supports tenant identification at two points in the request lifecycle: at the beginning of the routing phase (after route matching) and during middleware execution. Configuration is managed via `sprout.core.hooks`. ### Hook 1: Beginning of Routing Phase - **Timing**: Immediately after a route is matched. - **Tenant Availability**: Available for dependency injection throughout the entire middleware stack. ### Hook 2: During Middleware Execution - **Timing**: During the running of middleware. - **Tenant Availability**: Available for the controller/route handler, but not for other middleware constructors. Ensure identification middleware has higher priority if needed in other middleware. ### Configuration Enable/disable hooks using the `sprout.core.hooks` configuration option. ``` -------------------------------- ### Configure Route Parameter Pattern for Resolvers (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This configuration snippet shows how to define a regular expression constraint for a route parameter used by an identity resolver. The 'pattern' option allows you to specify valid constraints for route parameters, ensuring correct tenant identification. Setting it to null removes the option. ```php 'subdomain' => [ 'driver' => 'subdomain', 'domain' => env('TENANTED_DOMAIN'), 'pattern' => '.*' ] ``` -------------------------------- ### Configure Header Identity Resolver in PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This snippet shows how to configure Sprout Laravel to use the header driver for tenant identification. It specifies the driver as 'header' and allows customization of the header name using the 'header' option. The default header name is '{Tenancy}-Identifier'. ```php 'header' => [ 'driver' => 'header', 'header' => '{Tenancy}-Identifier', ], ``` -------------------------------- ### Tenant Interface Methods in PHP Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md These methods define the contract for a tenant class in Sprout Laravel. `getTenantIdentifier` and `getTenantKey` retrieve the unique identifier and key respectively, while `getTenantIdentifierName` and `getTenantKeyName` return the corresponding attribute or column names. ```php public function getTenantIdentifier(): string; public function getTenantIdentifierName(): string; public function getTenantKey(): int|string; public function getTenantKeyName(): string; ``` -------------------------------- ### Configure Route Parameter Naming for Resolvers (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/tenant-resolution.md This configuration snippet demonstrates how to set a custom route parameter name for an identity resolver. It uses placeholders like {tenancy} and {resolver} which are dynamically replaced when the route is defined. This is crucial for identifying tenants based on route parameters. ```php 'subdomain' => [ 'driver' => 'subdomain', 'domain' => env('TENANTED_DOMAIN'), 'parameter' => '{tenancy}_{resolver}' ] ``` -------------------------------- ### Add Tenant Columns to Password Reset Table Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This SQL schema modification adds 'tenancy' and 'tenant_id' columns to the 'password_reset_tokens' table, enabling Sprout's tenant-aware password reset functionality. The 'tenant_id' should match the primary key type of your tenant model. ```sql Schema::create('password_reset_tokens', function (Blueprint $table) { $table->string('email')->primary(); $table->string('tenancy')->nullable();// [tl! ++] $table->unsignedBigInteger('tenant_id')->nullable();// [tl! ++] $table->string('token'); $table->timestamp('created_at')->nullable(); }); ``` -------------------------------- ### Configure Auth Service Override in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration replaces Laravel's default password broker and ensures auth guards are purged when accessing a new tenant. It utilizes Sprout's specific implementations for cache and database token repositories, with fallback functionality for non-tenant contexts. ```php 'auth' => [ 'driver' => \Sprout\Overrides\StackedOverride::class, 'overrides' => [ \Sprout\Overrides\AuthGuardOverride::class, \Sprout\Overrides\AuthPasswordOverride::class, ], ], ``` -------------------------------- ### Implement Optional Tenant Relationship in Laravel Model Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Demonstrates how to make a model's tenant relationship optional by implementing the OptionalTenant interface and using the BelongsToTenant concern. This allows models to not be associated with a tenant, preventing exceptions and automatic scoping to null when no tenant is present. Manual association of the tenant relation is required. ```php use Sprout\Attributes\TenantRelation; use Sprout\Database\Eloquent\Concern\BelongsToTenant; use Sprout\Database\Eloquent\Contracts\OptionalTenant; class Category extends Model implements OptionalTenant { use BelongsToTenant; #[TenantRelation] public function blog(): BelongsTo { return $this->belongsTo(Blog::class); } } ``` -------------------------------- ### Configure Hydrate Tenant Relation in Sprout Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Illustrates how to enable the 'hydrateTenantRelation' option within the Sprout Laravel configuration. This option optimizes the retrieval of child models by automatically hydrating and setting the tenant relation to the current tenant without requiring an additional database query. ```php 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::hydrateTenantRelation(), ], ], ``` -------------------------------- ### Configure Cookie Service Override in Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration enables Sprout's Cookie service override, ensuring that cookies created within a tenant context have appropriate settings for domain and path based on identity resolvers. It defaults to 'config/session.php' if no Sprout settings are present. ```php 'cookie' => [ 'driver' => \Sprout\Overrides\CookieOverride::class, ], ``` -------------------------------- ### Configure Sprout Job Override (PHP) Source: https://github.com/sprout-laravel/docs/blob/1.x/service-overrides.md This configuration registers the Sprout Job override, which ensures that jobs maintain their associated tenancies and tenants when queued and executed. It's registered under the 'job' key. ```php 'job' => [ 'driver' => \Sprout\Overrides\JobOverride::class, ], ``` -------------------------------- ### Configure Throw If Not Related Option in Sprout Laravel Source: https://github.com/sprout-laravel/docs/blob/1.x/tenants.md Demonstrates the configuration of the 'throwIfNotRelated' option in Sprout Laravel. When enabled, this option ensures that an exception is thrown if a model being retrieved does not belong to the current tenant, which is a crucial security measure to prevent data leakage across tenants. ```php 'tenants' => [ 'provider' => 'tenants', 'options' => [ TenancyOptions::throwIfNotRelated(), ], ], ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.