### Complete Laravel Canonical Setup Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md This example demonstrates a full setup including .env configuration, a Blade template with the canonical component, and the resulting HTML output. ```env APP_NAME="My App" APP_URL=https://example.com CANONICAL_DOMAIN=https://example.com CANONICAL_TRIM_TRAILING_SLASH=true ``` ```blade My Post

My Post

``` ```html My Post

My Post

``` -------------------------------- ### Multi-Domain Configuration Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Provides examples for configuring different canonical domains based on environments or subdomains. ```env # .env.local (local development) CANONICAL_DOMAIN=http://localhost:8000 # .env.staging CANONICAL_DOMAIN=https://staging.example.com # .env.production CANONICAL_DOMAIN=https://example.com ``` ```env # Main site CANONICAL_DOMAIN=https://example.com # Shop subdomain (different server) CANONICAL_DOMAIN=https://shop.example.com ``` -------------------------------- ### Access Canonical Configuration Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md Example demonstrating how to retrieve the base URL and trailing slash trimming preference using CanonicalConfigInterface. ```php $config = app(CanonicalConfigInterface::class); $domain = $config->getBaseUrl(); // https://example.com $trimSlashes = $config->shouldTrimTrailingSlash(); // true ``` -------------------------------- ### Published Configuration File Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md This is an example of the configuration file after it has been published using `php artisan vendor:publish --tag="canonical-config"`. It shows the default values and environment variable fallbacks. ```php env('CANONICAL_DOMAIN', env('APP_URL', 'http://localhost')), /* |-------------------------------------------------------------------------- | Trim Trailing Slash |-------------------------------------------------------------------------- | | Determines whether trailing slashes should be removed from generated | canonical URLs. When set to true, URLs like /blog/ will be normalized | to /blog. When set to false, the original URL format is preserved. | | @since 1.1.0 | */ 'trim_trailing_slash' => env('CANONICAL_TRIM_TRAILING_SLASH', true), ]; ``` -------------------------------- ### Canonical URL Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md These are examples of fully qualified URLs that can be generated. They follow the format {scheme}://{host}{path}{query}. ```text https://example.com https://example.com/blog https://example.com/blog/post https://example.com/search?q=test&page=2 http://localhost:8000/products/item ``` -------------------------------- ### Multi-domain Configuration Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Configure different canonical domains for staging and production environments by setting the CANONICAL_DOMAIN in respective .env files. ```env # .env.staging CANONICAL_DOMAIN=https://staging.example.com # .env.production CANONICAL_DOMAIN=https://example.com ``` -------------------------------- ### Configuration Merging Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Demonstrates how package default configuration, published configuration, and environment variables are merged. Environment variables have the highest precedence. ```php // Package default 'domain' => env('CANONICAL_DOMAIN', env('APP_URL', 'http://localhost')) // Can be overridden in published config // config/canonical.php return [ 'domain' => 'https://example.com', // Overrides defaults ]; // Environment variables override everything CANONICAL_DOMAIN=https://custom.com ``` -------------------------------- ### Generate Canonical URL Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md Example of how to retrieve and use the CanonicalUrlGeneratorInterface to generate a canonical URL. ```php $generator = app(CanonicalUrlGeneratorInterface::class); $url = $generator->generate('/blog/post'); ``` -------------------------------- ### Example .env File Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Illustrates how to set environment variables for the canonical domain and trailing slash trimming in a Laravel application. ```env # Laravel app URL (fallback for CANONICAL_DOMAIN) APP_URL=https://example.com # Canonical URL domain (overrides APP_URL) CANONICAL_DOMAIN=https://example.com # Trailing slash handling CANONICAL_TRIM_TRAILING_SLASH=true ``` -------------------------------- ### Install Laravel Canonical Package Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Install the package using Composer. Then, set the required environment variables for the canonical domain and trailing slash trimming. ```bash composer require fkrzski/laravel-canonical ``` ```env CANONICAL_DOMAIN=https://example.com CANONICAL_TRIM_TRAILING_SLASH=true ``` -------------------------------- ### Service Container Binding Retrieval Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md Demonstrates how to retrieve services from the container using class names, interface resolution, or the make() method. ```php // Using class name as key $generator = app(CanonicalUrlGeneratorInterface::class); // Using interface resolution $config = resolve(CanonicalConfigInterface::class); // Using make() $builder = app()->make(CanonicalUrlBuilderInterface::class); ``` -------------------------------- ### Install Laravel Canonical Package Source: https://github.com/fkrzski/laravel-canonical/blob/master/README.md Install the package using Composer. The package auto-registers via Laravel's package discovery. ```bash composer require fkrzski/laravel-canonical ``` -------------------------------- ### Build Canonical URL Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md Demonstrates how to use the `CanonicalUrlBuilderInterface` to construct a canonical URL. Ensure the interface is resolved via the application container. ```php $builder = app(CanonicalUrlBuilderInterface::class); $url = $builder->build('https://example.com', '/blog/post'); // Returns: https://example.com/blog/post ``` -------------------------------- ### Custom Canonical View Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md An example of a customized canonical view file. This demonstrates how to modify the default view to include additional attributes or logic. ```blade {{-- resources/views/vendor/canonical/components/canonical.blade.php --}} {{-- Modified to include additional attributes --}} ``` -------------------------------- ### Configuration Fallback Chain Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Illustrates the fallback chain for resolving the CANONICAL_DOMAIN. It shows scenarios where CANONICAL_DOMAIN is set, only APP_URL is set, and neither is set. ```env # Scenario 1: CANONICAL_DOMAIN is set CANONICAL_DOMAIN=https://shop.example.com APP_URL=https://example.com # Result: https://shop.example.com # Scenario 2: CANONICAL_DOMAIN not set, APP_URL is set APP_URL=https://example.com # Result: https://example.com # Scenario 3: Neither set # Result: http://localhost ``` -------------------------------- ### Set Canonical Domain in config/canonical.php Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Example configuration for the canonical domain within the config/canonical.php file. ```php // config/canonical.php return [ 'domain' => 'https://example.com', ]; ``` -------------------------------- ### CanonicalUrlBuilder Usage Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Demonstrates various scenarios for building canonical URLs, including basic construction, paths with query parameters, root paths, and custom trailing slash configurations. ```php $builder = app(CanonicalUrlBuilderInterface::class); // Basic construction with trailing slash trimming enabled $builder->build('https://example.com', '/blog'); // Returns: https://example.com/blog // Path with trailing slash (trimmed by default) $builder->build('https://example.com', '/blog/'); // Returns: https://example.com/blog // With query parameters $builder->build('https://example.com', '/search?q=test'); // Returns: https://example.com/search?q=test // Base URL with trailing slash (stripped internally) $builder->build('https://example.com/', '/blog'); // Returns: https://example.com/blog // Root path $builder->build('https://example.com', '/'); // Returns: https://example.com // With config trim_trailing_slash = false // Path with trailing slash is preserved $builder->build('https://example.com', '/blog/'); // Returns: https://example.com/blog/ ``` -------------------------------- ### Generate Canonical URL Examples Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Demonstrates how to use the Canonical facade to generate canonical URLs for the current request or custom paths. Preserves query parameters when generating for the current request. ```php use Fkrzski\LaravelCanonical\Facades\Canonical; // Current request URI Canonical::generate(); // Returns: https://example.com/blog/post // Custom path Canonical::generate('/products/item'); // Returns: https://example.com/products/item // With query parameters preserved // Request: GET /search?q=laravel&page=2 Canonical::generate(); // Returns: https://example.com/search?q=laravel&page=2 // Custom path overrides current request // Current request: /old-url Canonical::generate('/new-url'); // Returns: https://example.com/new-url ``` -------------------------------- ### Using Custom Path with Blade Component Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of providing a static custom path to the x-canonical component. ```blade ``` -------------------------------- ### Default Canonical Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Example of the default configuration file for the Laravel Canonical package, showing domain and trailing slash trimming settings. ```php return [ 'domain' => 'https://example.com', 'trim_trailing_slash' => true, ]; ``` -------------------------------- ### Get Generator Instance Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Demonstrates how to obtain an instance of the CanonicalUrlGeneratorInterface using the canonical() helper function for fluent URL generation. ```php $generator = canonical(); $url = $generator->generate('/blog'); ``` -------------------------------- ### Set Canonical Domain in .env Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Examples of how to set the canonical domain in the .env file. Option 1 sets CANONICAL_DOMAIN directly, while Option 2 uses APP_URL as a fallback. ```env # Option 1: Set CANONICAL_DOMAIN CANONICAL_DOMAIN=https://example.com # Option 2: Set APP_URL (if CANONICAL_DOMAIN not set) APP_URL=https://example.com ``` -------------------------------- ### Blade Component Usage Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Examples of how to use the 'canonical' Blade component in your views. You can pass a static path or a dynamic variable. ```blade ``` -------------------------------- ### Blade Template Usage: Fluent Interface Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of using the canonical() helper function with its fluent interface to generate a canonical URL in a Blade template. ```blade ``` -------------------------------- ### Laravel Canonical Configuration Flow Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Outlines the sequence of steps involved in loading and validating configuration for the Laravel Canonical package, starting from environment variables to the final generated URLs. ```text .env → config/canonical.php → CanonicalConfig ↓ BaseUrlValidator ↓ Validated config ↓ CanonicalUrlGenerator ↓ Generated URLs ``` -------------------------------- ### Using Current Request URL with Blade Component Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of using the x-canonical component without a path to utilize the current request URL. ```blade ``` -------------------------------- ### Validate Base URL Example Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/types.md Shows how to use the `BaseUrlValidatorInterface` to validate a URL. Catch `CanonicalConfigurationException` for invalid URLs. The interface is resolved via the application container. ```php $validator = app(BaseUrlValidatorInterface::class); try { $validator->validate('https://example.com'); // Validation passed } catch (CanonicalConfigurationException $e) { // Invalid URL } ``` -------------------------------- ### Resolve Invalid Canonical Domain URL Format Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Provides examples of valid and invalid URL formats for the CANONICAL_DOMAIN environment variable. Ensures the URL includes a scheme and host. ```env # ✗ Invalid CANONICAL_DOMAIN=example.com CANONICAL_DOMAIN=localhost:8000 # ✓ Valid CANONICAL_DOMAIN=https://example.com CANONICAL_DOMAIN=http://localhost:8000 ``` -------------------------------- ### Blade Template Usage: Direct Generation Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of using the canonical() helper function for direct canonical URL generation within a Blade template. ```blade ``` -------------------------------- ### Conditional Canonical Link Rendering Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md This example demonstrates how to conditionally render the canonical link tag based on the application's environment. It will only render if the environment is not 'development'. ```blade @if(config('app.env') !== 'development') @endif ``` -------------------------------- ### Feature Testing Canonical URL in Blade Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md This example shows how to perform feature testing for canonical URLs rendered in Blade views. It sets a test configuration for the canonical domain and asserts that the correct canonical link tag is present in the response. ```php public function test_canonical_url_in_blade() { config(['canonical.domain' => 'https://testing.local']); $response = $this->get('/blog/test-post'); $response->assertSee(' ``` -------------------------------- ### Development Environment Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Set temporary canonical and app URLs in .env.local to continue development when configuration is missing. ```env # .env.local CANONICAL_DOMAIN=http://localhost:8000 APP_URL=http://localhost:8000 ``` -------------------------------- ### Publish Configuration File Source: https://github.com/fkrzski/laravel-canonical/blob/master/README.md Publish the configuration file for the package using the Artisan command. This step is optional. ```bash php artisan vendor:publish --tag="canonical-config" ``` -------------------------------- ### Get Canonical Base URL Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Retrieves the configured canonical domain for the application. Ensure CanonicalConfigInterface is resolved via the application container. ```php $config = app(CanonicalConfigInterface::class); $domain = $config->getBaseUrl(); // Returns: https://example.com ``` -------------------------------- ### CanonicalServiceProvider - boot() Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Bootstraps services for the Canonical package, including loading views, registering Blade components and directives, and publishing assets. ```APIDOC ## CanonicalServiceProvider - boot() ### Description Bootstraps services and registers views/components. ### Behavior: - Loads views from `resources/views` namespace `canonical` - Registers `Canonical` Blade component as `` - Registers `@canonical` Blade directive - Publishes config file to `config/canonical.php` when running in console - Publishes views to `resources/views/vendor/canonical` when running in console ``` -------------------------------- ### Handle Configuration Exception During Application Boot Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Log critical configuration errors that occur early in the application's boot process within the service provider. This pattern is useful for immediate error reporting and potential fallback mechanisms. ```php public function boot(): void { try { // Requesting the config service triggers validation $config = app(CanonicalConfigInterface::class); } catch (CanonicalConfigurationException $e) { // Log configuration error Log::critical('Canonical configuration failed', [ 'error' => $e->getMessage(), ]); // Optionally disable canonical URL generation // or set a fallback configuration } } ``` -------------------------------- ### Manual Service Provider Registration (config/app.php) Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md If package discovery is disabled or manual registration is preferred, add the service provider and its alias to the 'providers' and 'aliases' arrays in config/app.php. ```php // config/app.php 'providers' => [ // ... Fkrzski\LaravelCanonical\CanonicalServiceProvider::class, ], 'aliases' => [ // ... 'Canonical' => Fkrzski\LaravelCanonical\Facades\Canonical::class, ] ``` -------------------------------- ### Bootstrapping Canonical Service Provider Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Illustrates the bootstrapping phase of the CanonicalServiceProvider where components and directives are registered. ```php CanonicalServiceProvider::boot() → Components/directives registered ``` -------------------------------- ### Main Entry Points for Laravel Canonical Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md Demonstrates various ways to generate canonical URLs using the helper function, facade, Blade component, and Blade directive. Also shows dependency injection usage. ```php // Helper function canonical('/path') // Returns: string URL canonical()->generate('/path') // Returns: string URL canonical()->generate() // Returns: string URL (current request) ``` ```php // Facade Canonical::generate('/path') Canonical::generate() ``` ```php // Blade component ``` ```php // Blade directive @canonical @canonical('/path') @canonical($variable) ``` ```php // Dependency injection public function __construct(CanonicalUrlGeneratorInterface $canonical) ``` -------------------------------- ### Configure Multi-Domain Canonical URLs via Environment Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md Handle different canonical domains per environment by setting the `CANONICAL_DOMAIN` in your `.env` files. The same code works across all environments. ```bash # .env.staging CANONICAL_DOMAIN=https://staging.example.com # .env.production CANONICAL_DOMAIN=https://example.com # .env.local (development) CANONICAL_DOMAIN=http://localhost:8000 ``` ```php $canonical = canonical()->generate('/blog'); // Staging: https://staging.example.com/blog // Production: https://example.com/blog // Local: http://localhost:8000/blog ``` -------------------------------- ### CanonicalServiceProvider - provides() Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Returns a list of service container bindings provided by the CanonicalServiceProvider. ```APIDOC ## CanonicalServiceProvider - provides() ### Description Returns a list of service container bindings provided by the CanonicalServiceProvider. ### Returns: `array` — List of service container bindings provided ```php [ BaseUrlValidatorInterface::class, CanonicalConfigInterface::class, CanonicalUrlBuilderInterface::class, CanonicalUrlGeneratorInterface::class, ] ``` ``` -------------------------------- ### Using Dynamic Path from Variable with Blade Component Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of using Blade's attribute binding to dynamically set the path for the x-canonical component. ```blade ``` -------------------------------- ### Run Package Tests Source: https://github.com/fkrzski/laravel-canonical/blob/master/README.md Execute the package's test suite using Composer. This is a standard command for verifying package functionality. ```bash composer test ``` -------------------------------- ### Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md The package can be configured via environment variables to control the base domain and trailing slash behavior. ```APIDOC ## Configuration ### Description Configure the behavior of the canonical URL generator. ### Environment Variables - **CANONICAL_DOMAIN** (string): Sets the base domain for generating absolute canonical URLs. Example: `https://example.com` - **CANONICAL_TRIM_TRAILING_SLASH** (boolean): Controls whether trailing slashes should be removed from URLs. Default: `true` ``` -------------------------------- ### Blade Template Usage: Current Request Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of generating the canonical URL for the current request within a Blade template using the canonical() helper function. ```blade ``` -------------------------------- ### Handle Canonical Configuration Exceptions Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Catch potential exceptions during configuration instantiation, such as missing domain or invalid URL formats. The exception messages provide details on the configuration error. ```php try { $config = app(CanonicalConfigInterface::class); } catch (CanonicalConfigurationException $e) { // Possible messages: // "Canonical domain is not set in config." // "Invalid URL format: '...'.." // "Invalid URL scheme for '...'." // "Missing host in URL: '...'." } ``` -------------------------------- ### Factory Pattern for CanonicalConfig Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Demonstrates the use of factory closures within the service container to instantiate complex services like CanonicalConfig. ```php $this->app->singleton(function (Application $app): CanonicalConfigInterface { $validator = $app->make(BaseUrlValidatorInterface::class); return new CanonicalConfig(validator: $validator); }); ``` -------------------------------- ### Production Monitoring for Configuration Errors Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Catch CanonicalConfigurationException and log critical details for investigation in a production environment. ```php catch (CanonicalConfigurationException $e) { Log::alert('Canonical URL configuration failed', [ 'error' => $e->getMessage(), 'canonical_domain' => env('CANONICAL_DOMAIN'), 'app_url' => env('APP_URL'), 'timestamp' => now()->toIso8601String(), ]); } ``` -------------------------------- ### Canonical Link with HTML Comments for Debugging Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Example of adding HTML comments for debugging purposes alongside the canonical link tag. It includes the current request path and the generation timestamp. ```blade {{-- Canonical URL for {{ request()->path() }} --}} ``` -------------------------------- ### Registering Services as Singletons Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Services are registered as singletons to ensure a single instance per application lifecycle, promoting thread safety due to immutable service instances and non-stored state. ```php $this->app->singleton(BaseUrlValidatorInterface::class, BaseUrlValidator::class); ``` -------------------------------- ### Request Services by Interface Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Access services by their interface using the application instance. Useful for retrieving specific service implementations. ```php $generator = app(CanonicalUrlGeneratorInterface::class); $config = resolve(CanonicalConfigInterface::class); $builder = app()->make(CanonicalUrlBuilderInterface::class); ``` -------------------------------- ### Including Locale in Canonical Path Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md For multi-language sites, include the locale prefix in the canonical path. This example shows route model binding with a locale prefix and how to generate the canonical URL within a controller. ```php // Route model binding with locale prefix Route::get('/{locale}/blog/{slug}', 'BlogController@show') ->where('locale', 'en|es|fr'); // In controller class BlogController { public function show($locale, $slug) { $path = "/{$locale}/blog/{$slug}"; $canonical = canonical($path); return view('blog.show', [ 'canonical_url' => $canonical, ]); } } ``` ```blade ``` -------------------------------- ### Access Configuration via Config Helper Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Access configuration values directly using the `config()` helper function. Supports direct access and type-safe access for boolean and string types. ```php // Direct access $domain = config('canonical.domain'); // string $trimSlash = config('canonical.trim_trailing_slash'); // bool // Type-safe access $domain = config()->string('canonical.domain'); $trimSlash = config()->boolean('canonical.trim_trailing_slash'); ``` -------------------------------- ### Handle Configuration Errors During Bootstrap Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Catch `CanonicalConfigurationException` when accessing services for the first time to handle invalid configuration. This typically occurs when the canonical domain or URL formats are not correctly set. ```php try { // Accessing generator triggers config validation $url = canonical()->generate('/blog'); } catch (CanonicalConfigurationException $e) { // Configuration error detected // Examples: // - "Canonical domain is not set in config." // - "Invalid URL format: '...' // - "Invalid URL scheme for '...' // - "Missing host in URL: '..." } ``` -------------------------------- ### Publish Configuration File Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Conditionally publishes the configuration file when the application is running in the console. Users can publish the configuration file using the specified artisan command. ```php if ($this->app->runningInConsole()) { $this->publishes([ __DIR__.'/../config/canonical.php' => config_path('canonical.php'), ], 'canonical-config'); } ``` -------------------------------- ### Project File Structure Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/README.md Overview of the directory structure for the Laravel Canonical project. This helps in locating specific documentation files and understanding the project's organization. ```text output/ ├── README.md # This file ├── index.md # Navigation hub ├── quick-reference.md # Cheat sheet ├── api-reference.md # Full API ├── types.md # Type definitions ├── configuration.md # Config guide ├── errors.md # Error handling ├── service-provider.md # Bootstrap ├── architecture.md # Design patterns ├── blade-integration.md # Templates └── usage-patterns.md # Usage examples ``` -------------------------------- ### Accessing Laravel Canonical Services Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md Illustrates how to retrieve various services of the Laravel Canonical package from the service container. ```php // Get generator $generator = app(CanonicalUrlGeneratorInterface::class); // Get configuration $config = app(CanonicalConfigInterface::class); // Get builder $builder = app(CanonicalUrlBuilderInterface::class); // Get validator $validator = app(BaseUrlValidatorInterface::class); ``` -------------------------------- ### Catching CanonicalConfigurationException Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Demonstrates how to catch a CanonicalConfigurationException when retrieving the canonical configuration. This is useful for handling errors related to missing or invalid canonical domain settings. ```php use Fkrzski\LaravelCanonical\Exceptions\CanonicalConfigurationException; try { $config = app(CanonicalConfigInterface::class); } catch (CanonicalConfigurationException $e) { // Handle missing or invalid canonical domain echo "Configuration error: " . $e->getMessage(); } ``` -------------------------------- ### Facade Usage Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md The `Canonical` facade offers static methods to generate canonical URLs, mirroring the functionality of the helper function. ```APIDOC ## Facade ### Description Provides static access to the canonical URL generation service. ### Usage ```php // Generate canonical URL for a specific path Canonical::generate('/path/to/resource'); // Generate canonical URL for the current request Canonical::generate(); ``` ### Returns string URL ``` -------------------------------- ### Laravel Canonical Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md Shows how to configure the domain and trailing slash behavior for canonical URLs using environment variables. ```env # Domain configuration CANONICAL_DOMAIN=https://example.com # Trailing slash control CANONICAL_TRIM_TRAILING_SLASH=true # Default: true ``` -------------------------------- ### Catch CanonicalConfigurationException for Missing Domain Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Demonstrates how to catch a CanonicalConfigurationException and specifically handle the case where the canonical domain is not set. ```php use Fkrzski\LaravelCanonical\Exceptions\CanonicalConfigurationException; use Fkrzski\LaravelCanonical\Contracts\CanonicalConfigInterface; try { $config = app(CanonicalConfigInterface::class); } catch (CanonicalConfigurationException $e) { if (str_contains($e->getMessage(), 'not set in config')) { // Handle missing domain configuration Log::error('Canonical domain configuration missing', [ 'message' => $e->getMessage(), ]); } } ``` -------------------------------- ### CanonicalUrlBuilder Constructor Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Initializes the CanonicalUrlBuilder with configuration settings. ```php public function __construct( CanonicalConfigInterface $config ): void ``` -------------------------------- ### CanonicalConfig Method Signatures Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Provides methods to retrieve the base URL and check if trailing slashes should be trimmed. These are essential for configuration management. ```php // Config CanonicalConfig::getBaseUrl(): string CanonicalConfig::shouldTrimTrailingSlash(): bool ``` -------------------------------- ### Generate Canonical URL with Helper Function Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Use the simplest helper function to generate a canonical URL for a given path. Ensure the CANONICAL_DOMAIN is set in your .env file. ```php canonical('/blog/post') // Returns: https://example.com/blog/post ``` -------------------------------- ### Configure Canonical Domain Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md Set the canonical domain and optionally control trailing slash behavior in your .env file. ```env CANONICAL_DOMAIN=https://example.com # Optional: Control trailing slash behavior (default: true) CANONICAL_TRIM_TRAILING_SLASH=true ``` -------------------------------- ### Publish Package Assets Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md Publish the package's configuration and views using Artisan commands. This makes the configuration file and Blade components available for customization. ```bash php artisan vendor:publish --tag="canonical-config" ``` ```bash php artisan vendor:publish --tag="canonical-views" ``` -------------------------------- ### Package Default Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md The package's default configuration file provides fallback values if not specified in environment variables or the published config file. ```php 'domain' => env('CANONICAL_DOMAIN', env('APP_URL', 'http://localhost')) ``` -------------------------------- ### CanonicalConfig Constructor Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Initializes CanonicalConfig with a BaseUrlValidatorInterface. Throws CanonicalConfigurationException if the canonical domain configuration is invalid. ```php public function __construct( BaseUrlValidatorInterface $validator ): void ``` -------------------------------- ### Set Canonical Domain Source: https://github.com/fkrzski/laravel-canonical/blob/master/README.md Configure the canonical domain for your application in the .env file. If not set, it defaults to APP_URL. ```env CANONICAL_DOMAIN=https://example.com ``` -------------------------------- ### CanonicalUrlGenerator Dependency Tree Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Illustrates the dependency relationships for the CanonicalUrlGenerator, showing its reliance on configuration and URL building interfaces. ```text CanonicalUrlGenerator ├── CanonicalConfigInterface │ ├── Domain (string) │ └── TrimTrailingSlash (bool) │ └── BaseUrlValidatorInterface └── CanonicalUrlBuilderInterface └── CanonicalConfigInterface ``` -------------------------------- ### First Use Validation in Canonical Services Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Details the validation process that occurs on the first access to canonical services, potentially throwing a CanonicalConfigurationException. ```php First access to canonical services → CanonicalConfig::__construct() → BaseUrlValidator::validate() → CanonicalConfigurationException thrown if invalid → OR services initialized successfully ``` -------------------------------- ### Handle Configuration Resolution Exception Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Catch configuration exceptions when resolving services from the container. This ensures that the application handles invalid configurations gracefully before proceeding. ```php use Fkrzski\LaravelCanonical\Exceptions\CanonicalConfigurationException; use Fkrzski\LaravelCanonical\Contracts\CanonicalConfigInterface; try { // Configuration is validated here, on first resolution $config = app(CanonicalConfigInterface::class); // Generator is also resolved, which depends on config $generator = app(CanonicalUrlGeneratorInterface::class); } catch (CanonicalConfigurationException $e) { // Handle any configuration error abort(500, "Canonical URL configuration error: " . $e->getMessage()); } ``` -------------------------------- ### Safe Canonical URL Generation Methods Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md After successful initialization, these methods for generating canonical URLs will not throw exceptions. ```php canonical()->generate(); // No exceptions thrown canonical()->generate('/path'); // No exceptions thrown canonical()/path'); // No exceptions thrown Canonical::generate(); // No exceptions thrown // No exceptions thrown @canonical // No exceptions thrown @canonical('/path') // No exceptions thrown ``` -------------------------------- ### Directly Access Canonical Services from Container Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md Access the canonical URL generator and configuration services directly from the application container when needed. Requires importing relevant interfaces. ```php use Fkrzski\LaravelCanonical\Contracts\CanonicalUrlGeneratorInterface; use Fkrzski\LaravelCanonical\Contracts\CanonicalConfigInterface; // Get the canonical URL generator $generator = app(CanonicalUrlGeneratorInterface::class); $url = $generator->generate('/products'); // Get configuration directly $config = app(CanonicalConfigInterface::class); $domain = $config->getBaseUrl(); // https://example.com $trimSlash = $config->shouldTrimTrailingSlash(); // true ``` -------------------------------- ### Helper Function: canonical() Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md The global `canonical()` helper function provides a convenient way to generate canonical URLs. It can be used for fluent chaining or directly generate a URL with a given path. ```APIDOC ## Helper Function: canonical() Global helper function for canonical URL generation with dual return type based on arguments. **File:** `src/helpers.php` ### Signature ```php function canonical(?string $path = null): CanonicalUrlGeneratorInterface|string ``` **Parameters:** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `$path` | `string|null` | No | `null` | Optional path to generate URL for. If null, returns the generator instance | **Returns:** - When `$path` is `null`: `CanonicalUrlGeneratorInterface` — Generator instance for fluent chaining - When `$path` is provided: `string` — The generated canonical URL **Usage Examples:** ```php // Get generator instance for fluent usage $url = canonical()->generate('/products/item'); // Returns: string // Generate URL directly with path $url = canonical('/products/item'); // Returns: string (https://example.com/products/item) // Use current request URL $url = canonical()->generate(); // Returns: string (current page's canonical URL) // In Blade templates ``` ``` -------------------------------- ### Configure Canonical Domain and Trailing Slash (Bash) Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Set the required CANONICAL_DOMAIN and optional CANONICAL_TRIM_TRAILING_SLASH environment variables to control the package's behavior. ```bash # REQUIRED (or APP_URL as fallback) CANONICAL_DOMAIN=https://example.com ``` ```bash # OPTIONAL (default: true) CANONICAL_TRIM_TRAILING_SLASH=true ``` -------------------------------- ### Generate Canonical URL with Fluent Interface Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md Obtain the generator instance using `canonical()` and chain methods for fluent URL generation. Suitable when multiple operations are needed or fluent syntax is preferred. ```php // Returns the CanonicalUrlGeneratorInterface instance $generator = canonical(); // Chain the generate method $url = canonical()->generate('/products/item'); // Generate current request URL $url = canonical()->generate(); // Use in Blade ``` -------------------------------- ### Generate Canonical URL with Facade Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Use the Canonical facade to generate canonical URLs. This provides a static interface for generating URLs. ```php Canonical::generate('/blog/post') Canonical::generate() ``` -------------------------------- ### Canonical Configuration Constructor Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Shows the PHP code for the CanonicalConfig constructor, including domain retrieval, trimming, and validation. ```php public function __construct(BaseUrlValidatorInterface $validator) { $domain = config()->string('canonical.domain'); if (empty($domain)) { throw new CanonicalConfigurationException( 'Canonical domain is not set in config.' ); } $trimmedDomain = trim($domain, '/'); $validator->validate($trimmedDomain); $this->baseUrl = $trimmedDomain; $this->trimTrailingSlash = config()->boolean('canonical.trim_trailing_slash'); } ``` -------------------------------- ### Merge Package Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Merges the default configuration from the package. Published configuration files will override these values. ```php $this->mergeConfigFrom( __DIR__.'/../config/canonical.php', 'canonical' ); ``` -------------------------------- ### Canonical Facade Method Signature Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Provides a static proxy to the generator service, allowing for easy access to canonical URL generation methods. ```php // Facade Canonical::generate(?string $path = null): string ``` -------------------------------- ### Mock CanonicalConfigInterface for Testing Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Bind a mock implementation of `CanonicalConfigInterface` to the service container to control configuration during tests. This allows for isolated testing of components that rely on canonical URL generation. ```php use Fkrzski\LaravelCanonical\Contracts\CanonicalConfigInterface; public function test_custom_configuration() { $mockConfig = new class implements CanonicalConfigInterface { public function getBaseUrl(): string { return 'https://test.local'; } public function shouldTrimTrailingSlash(): bool { return false; } }; $this->app->bind(CanonicalConfigInterface::class, fn () => $mockConfig); $url = canonical('/blog/'); $this->assertEquals('https://test.local/blog/', $url); } ``` -------------------------------- ### Facade for Canonical URL Generation Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Shows how the Canonical facade provides static access to the CanonicalUrlGeneratorInterface, proxying calls to the container instance. ```php Canonical::generate('/path'); // Proxies to container instance ``` -------------------------------- ### Multiple Canonical Links (Alternative Versions) Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md This snippet shows how to include multiple canonical and alternate links. It renders a canonical link and an alternate link for the homepage if the current URL is not the homepage. ```blade @if($canonicalUrl() !== url('/')) @endif ``` -------------------------------- ### Handle Optional Canonical URL Generation Exception Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/errors.md Implement exception handling for optional canonical URL generation, returning null instead of failing the request. This is suitable for scenarios where canonical URLs are not critical for core functionality. ```php use Fkrzski\LaravelCanonical\Exceptions\CanonicalConfigurationException; use Fkrzski\LaravelCanonical\Contracts\CanonicalUrlGeneratorInterface; function getCanonicalUrl(?string $path = null): ?string { try { return app(CanonicalUrlGeneratorInterface::class)->generate($path); } catch (CanonicalConfigurationException $e) { // Log the error Log::warning('Canonical URL generation failed', [ 'error' => $e->getMessage(), 'path' => $path, ]); // Return null instead of failing return null; } } ``` -------------------------------- ### Registering Canonical Service Provider Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Shows the registration phase of the CanonicalServiceProvider where services are registered but not yet validated. ```php CanonicalServiceProvider::register() → Services registered (deferred, no validation yet) ``` -------------------------------- ### Generate Canonical URL with Helper Fluent API Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Utilize the fluent API of the helper function to generate canonical URLs. You can specify a path or use the current request's path. ```php canonical()->generate('/blog/post') canonical()->generate() // Current request ``` -------------------------------- ### Handle Canonical Configuration Errors with Directives Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/blade-integration.md Use PHP's try-catch block within a @php directive to handle canonical configuration exceptions when using the directive. Logs warnings for errors. ```blade @php try { echo sprintf('', e(canonical()->generate())); } catch (Fkrzski\LaravelCanonical\Exceptions\CanonicalConfigurationException $e) { Log::warning('Canonical error: ' . $e->getMessage()); } @endphp ``` -------------------------------- ### CanonicalUrlBuilder::build() Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Constructs a normalized canonical URL by combining a base URL and a path, applying configurable trailing slash rules. ```APIDOC ## CanonicalUrlBuilder::build() ### Description Constructs a normalized canonical URL by combining base URL and path. ### Method `public function build(string $baseUrl, string $path): string` ### Parameters #### Path Parameters - **baseUrl** (string) - Required - The canonical domain (e.g., `https://example.com`) - **path** (string) - Required - The request path with optional query parameters (e.g., `/blog/post?id=1`) ### Returns `string` - Fully constructed and normalized canonical URL ### Behavior - Strips trailing slashes from both baseUrl and path, then trims slashes from path - If `trim_trailing_slash` is `false` in config, preserves trailing slashes from the path - For root paths, returns either `baseUrl/` or `baseUrl` depending on configuration and input - Combines base URL and path with a single slash ### Usage Examples ```php $builder = app(CanonicalUrlBuilderInterface::class); // Basic construction with trailing slash trimming enabled $builder->build('https://example.com', '/blog'); // Returns: https://example.com/blog // Path with trailing slash (trimmed by default) $builder->build('https://example.com', '/blog/'); // Returns: https://example.com/blog // With query parameters $builder->build('https://example.com', '/search?q=test'); // Returns: https://example.com/search?q=test // Base URL with trailing slash (stripped internally) $builder->build('https://example.com/', '/blog'); // Returns: https://example.com/blog // Root path $builder->build('https://example.com', '/'); // Returns: https://example.com // With config trim_trailing_slash = false // Path with trailing slash is preserved $builder->build('https://example.com', '/blog/'); // Returns: https://example.com/blog/ ``` ``` -------------------------------- ### Configure Canonical Domain Source: https://github.com/fkrzski/laravel-canonical/blob/master/README.md Set the canonical domain in the configuration file. This is useful for multi-domain environments to specify the primary domain. ```php // config/canonical.php return [ 'domain' => env('CANONICAL_DOMAIN', config('app.url')), ]; ``` -------------------------------- ### Helper Function Usage Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md The `canonical()` helper function provides a convenient way to generate canonical URLs. It can be called with a path or used to access a generator instance. ```APIDOC ## Helper Function ### Description Provides a fluent interface for generating canonical URLs. ### Usage ```php // Generate canonical URL for a specific path canonical('/path/to/resource'); // Access generator instance to generate URL for a specific path canonical()->generate('/path/to/resource'); // Access generator instance to generate URL for the current request canonical()->generate(); ``` ### Returns string URL ``` -------------------------------- ### Subsequent Use of Canonical Services Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Explains that subsequent URL generations do not require validation and use cached configuration values. ```php URL generation → No validation needed → Uses cached config values → No exceptions thrown ``` -------------------------------- ### Custom Canonical Generator Implementation Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Shows how to implement a custom canonical URL generator by extending the CanonicalUrlGeneratorInterface and registering it in the service provider. ```php class CustomCanonicalGenerator implements CanonicalUrlGeneratorInterface { public function generate(?string $path = null): string { // Custom logic } } // Register in service provider app()->bind(CanonicalUrlGeneratorInterface::class, CustomCanonicalGenerator::class); ``` -------------------------------- ### Helper Function Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md The `canonical()` helper function provides a convenient way to generate canonical URLs. It can be called with a path or without a path to use the current request's URL. ```APIDOC ## Helper Function ### Description Use the `canonical()` helper function to generate canonical URLs. You can provide a specific path or omit it to use the current request's URL. ### Usage ```php canonical('/path') // Returns a string canonical()->generate('/path') // Returns a string canonical()->generate() // Returns a string (for the current request) ``` ``` -------------------------------- ### Register CanonicalConfigInterface Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/service-provider.md Registers the configuration handler as a singleton using a factory closure. It depends on BaseUrlValidatorInterface. ```php $this->app->singleton(function (Application $app): CanonicalConfigInterface { /** @var BaseUrlValidatorInterface $validator */ $validator = $app->make(BaseUrlValidatorInterface::class); return new CanonicalConfig( validator: $validator, ); }); ``` -------------------------------- ### Generate Canonical URL with Trailing Slash Options Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/configuration.md Demonstrates how the `generate` method behaves with `trim_trailing_slash` set to true or false. Query parameters are always preserved. ```php // With trim_trailing_slash = true canonical()->generate('/blog/'); // https://example.com/blog // With trim_trailing_slash = false canonical()->generate('/blog/'); // https://example.com/blog/ // Query parameters always preserved canonical()->generate('/search?q=test&page=2'); // https://example.com/search?q=test&page=2 ``` -------------------------------- ### Canonical Facade - generate() Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/api-reference.md Generates the canonical URL for a given path or the current request using the Canonical facade. ```APIDOC ## Canonical Facade - generate() ### Description Generates canonical URL for the given path or current request. ### Method ```php Canonical::generate(?string $path = null): string ``` ### Usage Examples: ```php use Fkrzski\LaravelCanonical\Facades\Canonical; // Current request Canonical::generate(); // https://example.com/blog/post // Custom path Canonical::generate('/products'); // https://example.com/products // In Blade ``` ``` -------------------------------- ### URL Normalization with Trailing Slash Trimmed Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/quick-reference.md Demonstrates how the package trims trailing slashes from URLs by default when CANONICAL_TRIM_TRAILING_SLASH is true. ```text Input: /blog/ Output: https://example.com/blog Input: /blog Output: https://example.com/blog Input: /search?q=test Output: https://example.com/search?q=test Input: / Output: https://example.com ``` -------------------------------- ### Test Canonical URL with Custom Configuration Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/index.md Temporarily override the package's configuration, such as the domain, within your PHP code for testing purposes. This allows you to verify URL generation with specific settings. ```php config(['canonical.domain' => 'https://test.local']); $url = canonical('/path'); ``` -------------------------------- ### Custom Canonical View Component Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/architecture.md Demonstrates how to publish and customize the default canonical view component, including adding custom attributes. ```blade ``` -------------------------------- ### Configure Subdomain Canonical URLs Source: https://github.com/fkrzski/laravel-canonical/blob/master/_autodocs/usage-patterns.md Handle different subdomains with separate canonical domains by setting `CANONICAL_DOMAIN` in the environment or using route middleware for conditional domains. ```env # For main site CANONICAL_DOMAIN=https://example.com # For shop subdomain (if run separately) CANONICAL_DOMAIN=https://shop.example.com ``` ```php // In your service provider or middleware Route::middleware('set-canonical-domain')->group(function () { // Routes where CANONICAL_DOMAIN=https://shop.example.com }); ```