### Install and Setup Short URL Package Source: https://context7.com/ash-jc-allen/short-url/llms.txt Install the package using Composer and publish its configuration and migration files. Run migrations to create the necessary database tables. ```bash composer require ashallendesign/short-url # Publish config and migrations php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider" # Run migrations (creates short_urls and short_url_visits tables) php artisan migrate ``` -------------------------------- ### Implement Custom UserAgentDriver Source: https://context7.com/ash-jc-allen/short-url/llms.txt Swap out the default user-agent parsing library by implementing the `UserAgentDriver` interface and configuring it. This example uses a mock parsing logic. ```php namespace App\Services; use AshAllenDesign\ShortURL\Interfaces\UserAgentDriver; class BrowscapDriver implements UserAgentDriver { private array $parsed = []; public function usingUserAgentString(?string $userAgentString): self { // parse with your preferred library $this->parsed = ['browser' => 'Firefox', 'os' => 'Linux', 'device' => 'desktop']; return $this; } public function getOperatingSystem(): ?string { return $this->parsed['os'] ?? null; } public function getOperatingSystemVersion(): ?string { return null; } public function getBrowser(): ?string { return $this->parsed['browser'] ?? null; } public function getBrowserVersion(): ?string { return null; } public function getDeviceType(): ?string { return $this->parsed['device'] ?? null; } public function isDesktop(): bool { return $this->getDeviceType() === 'desktop'; } public function isMobile(): bool { return $this->getDeviceType() === 'mobile'; } public function isTablet(): bool { return $this->getDeviceType() === 'tablet'; } public function isRobot(): bool { return $this->getDeviceType() === 'bot'; } } ``` ```php 'user_agent_driver' => \App\Services\BrowscapDriver::class, ``` -------------------------------- ### Set Destination URL with Builder Source: https://context7.com/ash-jc-allen/short-url/llms.txt Sets the destination URL for the short URL. The URL must start with an allowed scheme; otherwise, a ShortURLException is thrown. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Exceptions\ShortURLException; try { $shortURL = app(Builder::class) ->destinationUrl('https://example.com/very/long/path?ref=newsletter') ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/Ab3Xy echo $shortURL->url_key; // Ab3Xy echo $shortURL->destination_url; // https://example.com/very/long/path?ref=newsletter } catch (ShortURLException $e) { // URL did not start with an allowed scheme logger()->error('Short URL creation failed: ' . $e->getMessage()); } ``` -------------------------------- ### Configure Custom Database Connection Source: https://context7.com/ash-jc-allen/short-url/llms.txt Set the `connection` configuration key to specify a custom database connection for all Short URL models. This is useful for multi-tenant or split-database setups. ```php // config/short-url.php 'connection' => 'central_db', ``` ```php // Both models will now use the 'central_db' connection automatically: // ShortURL::all() → queries central_db.short_urls // ShortURLVisit::all() → queries central_db.short_url_visits // You can verify at runtime: $model = new \AshAllenDesign\ShortURL\Models\ShortURL(); echo $model->getConnectionName(); // 'central_db' ``` -------------------------------- ### Install Short URL Package via Composer Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Use Composer to add the Short URL package to your Laravel project. Ensure you meet the PHP and Laravel version requirements. ```bash composer require ashallendesign/short-url ``` -------------------------------- ### Builder::destinationUrl() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Sets the destination URL that the short URL will redirect visitors to. The URL must start with one of the allowed URL schemes. ```APIDOC ## `Builder::destinationUrl()` — Set the redirect target Sets the destination URL that the short URL will redirect visitors to. The URL must start with one of the `allowed_url_schemes` defined in config; throws `ShortURLException` otherwise. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Exceptions\ShortURLException; try { $shortURL = app(Builder::class) ->destinationUrl('https://example.com/very/long/path?ref=newsletter') ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/Ab3Xy echo $shortURL->url_key; // Ab3Xy echo $shortURL->destination_url; // https://example.com/very/long/path?ref=newsletter } catch (ShortURLException $e) { // URL did not start with an allowed scheme logger()->error('Short URL creation failed: ' . $e->getMessage()); } ``` ``` -------------------------------- ### Configure Tracking Fields Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Specify which fields to track for visits by default. Individual fields can be disabled here and overridden per URL. For example, IP address tracking is disabled in this configuration. ```php 'tracking' => [ ... 'fields' => [ 'ip_address' => false, 'operating_system' => true, 'operating_system_version' => true, 'browser' => true, 'browser_version' => true, 'referer_url' => true, 'device_type' => true, ], ], ``` -------------------------------- ### Get Tracked Fields for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Retrieve an array of fields that are currently enabled for tracking using the `trackingFields()` method. Note that these fields are only recorded if `track_visits` is also enabled. ```php $shortURL = \AshAllenDesign\\ShortURL\\Models\\ShortURL::first(); $shortURL->trackingFields(); ``` -------------------------------- ### Publish Short URL Migrations Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Run this command to publish the database migrations for the Short URL package to your project's migration directory. ```bash php artisan vendor:publish --tag="short-url-migrations" ``` -------------------------------- ### Configure Visit Tracking with `trackVisits()` and Field Methods Source: https://context7.com/ash-jc-allen/short-url/llms.txt Globally enable or disable visit tracking using `trackVisits()`. Granular control over individual tracking fields (IP, OS, browser, etc.) is available via dedicated methods. Settings default to `config/short-url.php` but can be overridden per URL. ```php use AshAllenDesign\ShortURL\Classes\Builder; // Track visits but record only browser name and device type $shortURL = app(Builder::class) ->destinationUrl('https://example.com/landing') ->trackVisits(true) ->trackIPAddress(false) ->trackOperatingSystem(false) ->trackOperatingSystemVersion(false) ->trackBrowser(true) ->trackBrowserVersion(false) ->trackRefererURL(false) ->trackDeviceType(true) ->make(); // Retrieve recorded visits later $visits = $shortURL->visits; // Eloquent HasMany collection of ShortURLVisit foreach ($visits as $visit) { echo $visit->browser; // e.g. "Chrome" echo $visit->device_type; // "desktop" | "mobile" | "tablet" | "robot" echo $visit->visited_at; // Carbon datetime } ``` -------------------------------- ### Run Unit Tests Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Execute the package's unit tests by running the provided command in your terminal. ```bash vendor/bin/phpunit ``` -------------------------------- ### Track Operating System Version for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable operating system version tracking for a shortened URL. Overrides the default configuration. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackOperatingSystemVersion() ->make(); ``` -------------------------------- ### Get Tracked Fields Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Retrieve an array of fields that are currently enabled for tracking for a short URL. Note that these fields are only recorded if the `track_visits` option is also enabled. ```APIDOC ### Tracked Fields To check which fields are enabled for tracking for a short URL, you can use the `->trackingFields()` method. It will return an array with the names of each field that is currently enabled for tracking. ```php $shortURL = \AshAllenDesign\ShortURL\Models\ShortURL::first(); $shortURL->trackingFields(); ``` ``` -------------------------------- ### Static Access to Builder via `ShortURL` Facade Source: https://context7.com/ash-jc-allen/short-url/llms.txt The `ShortURL` facade provides static proxy access to all `Builder` methods, returning a fresh `Builder` instance on each call. It allows for fluent, static configuration of short URLs and manual registration of routes. ```php use AshAllenDesign\ShortURL\Facades\ShortURL; use Carbon\Carbon; // Full-featured creation via facade $shortURL = ShortURL::destinationUrl('https://example.com/promo') ->urlKey('summer-sale') ->singleUse() ->secure() ->forwardQueryParams() ->redirectStatusCode(302) ->trackVisits() ->trackIPAddress() ->trackBrowser() ->trackDeviceType() ->activateAt(Carbon::now()->addHours(2)) ->deactivateAt(Carbon::now()->addWeek()) ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/summer-sale echo $shortURL->single_use; // true echo $shortURL->forward_query_params; // true // Register short URL routes manually (when disable_default_route = true) ShortURL::routes(); ``` -------------------------------- ### Get Visits for a Shortened URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Access the visits for a shortened URL using the `visits` relationship on the ShortURL model. This can be used like any other Laravel model relation. ```php $shortURL = \AshAllenDesign\\ShortURL\\Models\\ShortURL::find(1); $visits = $shortURL->visits; ``` -------------------------------- ### Get Visits for a Shortened URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md The `ShortURL` model provides a relationship to retrieve all visits associated with a shortened URL. Access this using the `visits` property or method. ```APIDOC ## Helper Methods ### Visits The ShortURL model includes a relationship for getting the visits for a shortened URL. ```php $shortURL = \AshAllenDesign\ShortURL\Models\ShortURL::find(1); $visits = $shortURL->visits; ``` ``` -------------------------------- ### Track Operating System for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable operating system name tracking for a shortened URL. Overrides the default configuration. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackOperatingSystem() ->make(); ``` -------------------------------- ### Run Database Migrations in Laravel Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Execute this Artisan command to apply new database migrations, which add necessary columns to the `short_urls` table for features like activation and deactivation dates. ```bash php artisan migrate ``` -------------------------------- ### Create ShortURL Model Factory Instances Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Utilize the package's model factories for testing purposes. Includes states for creating deactivated or inactive URLs. ```php use AshAllenDesign\ShortURL\Models\ShortURL; $shortUrl = ShortURL::factory()->create(); // URL is deactivated $deactivatedShortUrl = ShortURL::factory()->deactivated()->create(); // URL is neither activated nor deactivated $inactiveShortURL = ShortURL::factory()->inactive()->create(); ``` -------------------------------- ### Create Shortened URL Using Facade Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Utilize the `ShortURL` facade as an alternative to directly instantiating the `Builder` class for creating shortened URLs. ```php make(); ... } } ``` -------------------------------- ### Builder::trackVisits() and per-field tracking methods Source: https://context7.com/ash-jc-allen/short-url/llms.txt Enables or disables visit tracking globally for a URL, and provides granular control over each tracked field. All settings default to the values in `config/short-url.php`; calling any method overrides the config for this URL only. ```APIDOC ## `Builder::trackVisits()` and per-field tracking methods Enables or disables visit tracking globally for a URL, and provides granular control over each tracked field. All settings default to the values in `config/short-url.php`; calling any method overrides the config for this URL only. ```php use AshAllenDesign\ShortURL\Classes\Builder; // Track visits but record only browser name and device type $shortURL = app(Builder::class) ->destinationUrl('https://example.com/landing') ->trackVisits(true) ->trackIPAddress(false) ->trackOperatingSystem(false) ->trackOperatingSystemVersion(false) ->trackBrowser(true) ->trackBrowserVersion(false) ->trackRefererURL(false) ->trackDeviceType(true) ->make(); // Retrieve recorded visits later $visits = $shortURL->visits; // Eloquent HasMany collection of ShortURLVisit foreach ($visits as $visit) { echo $visit->browser; // e.g. "Chrome" echo $visit->device_type; // "desktop" | "mobile" | "tablet" | "robot" echo $visit->visited_at; // Carbon datetime } ``` ``` -------------------------------- ### Set Activation Time for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Schedule a short URL to become active at a future time using the `->activateAt()` method with a Carbon instance. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->activateAt("Carbon\Carbon"::now()->addDay()) ->make(); ``` -------------------------------- ### ShortURL Facade Source: https://context7.com/ash-jc-allen/short-url/llms.txt Provides static proxy access to all Builder methods. Each facade call returns a fresh Builder instance. ```APIDOC ## `ShortURL` Facade — Static access to the Builder A Laravel facade providing static proxy access to all `Builder` methods. Bound to `short-url.builder` in the container; each facade call returns a fresh `Builder` instance. ```php use AshAllenDesign\ShortURL\Facades\ShortURL; use Carbon\Carbon; // Full-featured creation via facade $shortURL = ShortURL::destinationUrl('https://example.com/promo') ->urlKey('summer-sale') ->singleUse() ->secure() ->forwardQueryParams() ->redirectStatusCode(302) ->trackVisits() ->trackIPAddress() ->trackBrowser() ->trackDeviceType() ->activateAt(Carbon::now()->addHours(2)) ->deactivateAt(Carbon::now()->addWeek()) ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/summer-sale echo $shortURL->single_use; // true echo $shortURL->forward_query_params; // true // Register short URL routes manually (when disable_default_route = true) ShortURL::routes(); ``` ``` -------------------------------- ### Builder::beforeCreate() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Provides a Closure that receives the ShortURL model instance just before it is saved. Use this to attach custom fields (e.g., tenant ID, user ID) without modifying the package. ```APIDOC ## `Builder::beforeCreate()` — Mutate model before persisting Provides a `Closure` that receives the `ShortURL` model instance just before it is saved. Use this to attach custom fields (e.g., tenant ID, user ID) without modifying the package. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Models\ShortURL; $tenantId = auth()->user()->tenant_id; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/resource') ->beforeCreate(function (ShortURL $model) use ($tenantId): void { $model->tenant_id = $tenantId; // custom column added via your own migration }) ->make(); echo $shortURL->tenant_id; // the tenant ID set in the closure ``` ``` -------------------------------- ### Publish Short URL Migrations in Laravel Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Run this command to publish the Short URL package's migration files. This allows you to modify them before running `php artisan migrate`. ```bash php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider" ``` -------------------------------- ### Enable URL Visit Tracking Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Override the default configuration to explicitly enable visit tracking for a specific short URL using `->trackVisits()`. This method defaults to true if no argument is provided. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->make(); ``` -------------------------------- ### Configure Short URL Package Source: https://context7.com/ash-jc-allen/short-url/llms.txt The central configuration file `config/short-url.php` controls all package behavior. Adjust settings such as the route prefix, default URL, middleware, HTTPS enforcement, key length, and tracking options. ```php // config/short-url.php return [ // Route prefix for the default redirect route: /short/{key} 'prefix' => '/short', // Override the base URL used in default_short_url; null = app.url 'default_url' => null, // e.g. 'https://sho.rt' // Extra middleware applied to the default route 'middleware' => [], // e.g. ['web', ThrottleRequests::class] // Disable the auto-registered default route entirely 'disable_default_route' => false, // Always upgrade destination URLs to HTTPS on creation 'enforce_https' => true, // Forward query params from short URL to destination by default 'forward_query_params' => false, // Allowed destination URL schemes 'allowed_url_schemes' => ['http://', 'https://'], // Minimum generated key length (acts as minimum, not fixed) 'key_length' => 5, // Salt used by Hashids 'key_salt' => 'AshAllenDesign\ShortURL', // Characters allowed in generated keys (must be ≥16 unique chars, no spaces) 'alphabet' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890', // Custom database connection for both models (null = default) 'connection' => null, // Validate config values on boot (recommended in production) 'validate_config' => true, // Visitor tracking defaults (all overridable per URL at build time) 'tracking' => [ 'default_enabled' => true, 'fields' => [ 'ip_address' => true, 'operating_system' => true, 'operating_system_version' => true, 'browser' => true, 'browser_version' => true, 'referer_url' => true, 'device_type' => true, ], ], // Swappable driver classes 'user_agent_driver' => \AshAllenDesign\ShortURL\Classes\UserAgent\ParserPhpDriver::class, 'url_key_generator' => \AshAllenDesign\ShortURL\Classes\KeyGenerator::class, // Model factory overrides 'factories' => [ \AshAllenDesign\ShortURL\Models\ShortURL::class => \AshAllenDesign\ShortURL\Models\Factories\ShortURLFactory::class, \AshAllenDesign\ShortURL\Models\ShortURLVisit::class => \AshAllenDesign\ShortURL\Models\Factories\ShortURLVisitFactory::class, ], ]; ``` -------------------------------- ### Enable Browser Version Tracking Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable tracking of the visitor's browser version using the `->trackBrowserVersion()` method. This method defaults to true if no argument is provided. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackBrowserVersion() ->make(); ``` -------------------------------- ### Conditionally Set Activation Time with 'when' Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Use the `when` method to conditionally apply the `activateAt` setting based on the presence of activation date information from a request. ```php use AshAllenDesign\ShortURL\Classes\Builder; use Carbon\Carbon; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->when( $request->date('activation'), function (Builder $builder, Carbon $activateDate): Builder { return $builder->activateAt($activateDate); }, ) ->make(); ``` -------------------------------- ### Track Device Type for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable device type tracking for a shortened URL. Overrides the default configuration. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackDeviceType() ->make(); ``` -------------------------------- ### Track Referer URL for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable referer URL tracking for a shortened URL. Overrides the default configuration. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackRefererURL() ->make(); ``` -------------------------------- ### Mutate ShortURL Model Before Creation with `beforeCreate()` Source: https://context7.com/ash-jc-allen/short-url/llms.txt The `beforeCreate()` method accepts a closure to modify the `ShortURL` model instance just before it's saved. This is ideal for adding custom fields like tenant or user IDs without altering the package's core files. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Models\ShortURL; $tenantId = auth()->user()->tenant_id; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/resource') ->beforeCreate(function (ShortURL $model) use ($tenantId): void { $model->tenant_id = $tenantId; // custom column added via your own migration }) ->make(); echo $shortURL->tenant_id; // the tenant ID set in the closure ``` -------------------------------- ### Enable IP Address Tracking Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable IP address tracking for a short URL by using the `->trackIPAddress()` method. This method defaults to true if no argument is provided. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackIPAddress() ->make(); ``` -------------------------------- ### Builder::activateAt() / Builder::deactivateAt() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Sets the activation and deactivation times for the short URL. Before activation or after deactivation, visitors will receive an HTTP 404. ```APIDOC ## `Builder::activateAt()` / `Builder::deactivateAt()` — Schedule URL lifetime Sets the datetime window during which the short URL is active. Before `activated_at` or after `deactivated_at`, visitors receive HTTP 404. Both dates must be in the future; `deactivateAt` must not precede `activateAt`. ```php use AshAllenDesign\ShortURL\Classes\Builder; use Carbon\Carbon; // Active from tomorrow, expires in 7 days — ideal for campaign URLs $shortURL = app(Builder::class) ->destinationUrl('https://example.com/black-friday') ->activateAt(Carbon::now()->addDay()) ->deactivateAt(Carbon::now()->addDays(8)) ->make(); echo $shortURL->activated_at->toDateTimeString(); // 2024-11-21 ... echo $shortURL->deactivated_at->toDateTimeString(); // 2024-11-28 ... ``` ``` -------------------------------- ### Schedule URL Lifetime with Builder Source: https://context7.com/ash-jc-allen/short-url/llms.txt Sets the activation and deactivation times for a short URL. The URL is inactive before `activated_at` and after `deactivated_at`, returning HTTP 404. Both dates must be in the future, and `deactivateAt` must not precede `activateAt`. ```php use AshAllenDesign\ShortURL\Classes\Builder; use Carbon\Carbon; // Active from tomorrow, expires in 7 days — ideal for campaign URLs $shortURL = app(Builder::class) ->destinationUrl('https://example.com/black-friday') ->activateAt(Carbon::now()->addDay()) ->deactivateAt(Carbon::now()->addDays(8)) ->make(); echo $shortURL->activated_at->toDateTimeString(); // 2024-11-21 ... echo $shortURL->deactivated_at->toDateTimeString(); // 2024-11-28 ... ``` -------------------------------- ### Find Short URLs by Key or Destination Source: https://context7.com/ash-jc-allen/short-url/llms.txt Use static finders on the ShortURL model to retrieve specific short URLs by their unique key or by their original destination URL. Access properties like destination URL, default short URL, and redirect status code. ```php use AshAllenDesign\ShortURL\Models\ShortURL; // Find by URL key $shortURL = ShortURL::findByKey('Ab3Xy'); if ($shortURL) { echo $shortURL->destination_url; // https://example.com/... echo $shortURL->default_short_url; // https://yourapp.com/short/Ab3Xy echo $shortURL->redirect_status_code; // 301 // Check tracking status if ($shortURL->trackingEnabled()) { $fields = $shortURL->trackingFields(); // ['ip_address', 'browser', 'browser_version', 'operating_system', ...] } // Access visit records $totalVisits = $shortURL->visits()->count(); $lastVisit = $shortURL->visits()->latest('visited_at')->first(); echo $lastVisit?->ip_address; echo $lastVisit?->browser; echo $lastVisit?->device_type; // 'desktop'|'mobile'|'tablet'|'robot' } // Find all short URLs pointing to the same destination $urls = ShortURL::findByDestinationURL('https://example.com/product/123'); // Returns Illuminate\Database\Eloquent\Collection foreach ($urls as $url) { echo $url->url_key . "\n"; } ``` -------------------------------- ### Configure Short URL Prefix Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Change the default '/short/' prefix for short URLs by updating the 'prefix' configuration value. Set to null to remove the prefix entirely. ```php 'prefix' => 's', ``` -------------------------------- ### Configure Forward Query Params Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Add this configuration option to your `config/short_urls.php` file to control the default behavior of forwarding query parameters. ```php /* |-------------------------------------------------------------------------- | Forwards query parameters |-------------------------------------------------------------------------- | | Here you can specify if the newly created short URLs will forward | the query parameters to the destination by default. This option | can be overridden when creating the short URL with the | ->forwardQueryParams() method. | | eg: https://yoursite.com/short/xxx?a=b => https://destination.com/page?a=b | */ 'forward_query_params' => false, ``` -------------------------------- ### Create Single-Use URL with Builder Source: https://context7.com/ash-jc-allen/short-url/llms.txt Marks the short URL as single-use. After the first visit, subsequent requests will result in an HTTP 404. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/download/invoice-2024.pdf') ->singleUse() // disable after first visit ->redirectStatusCode(302) // use 302 so browsers don't cache ->make(); // First visit → redirects to destination, records visit // Second visit → HTTP 404 ``` -------------------------------- ### Use ShortURL Eloquent Model Factories Source: https://context7.com/ash-jc-allen/short-url/llms.txt Utilize the provided Eloquent factories for `ShortURL` and `ShortURLVisit` to create test data. Includes states for deactivated and inactive URLs, and creating related visits. ```php use AshAllenDesign\ShortURL\Models\ShortURL; use AshAllenDesign\ShortURL\Models\ShortURLVisit; // Basic short URL with random data $shortUrl = ShortURL::factory()->create(); // A short URL that is currently deactivated (deactivated_at is in the past) $deactivated = ShortURL::factory()->deactivated()->create(); // A short URL with no activation or deactivation date $inactive = ShortURL::factory()->inactive()->create(); // Create a short URL with 5 associated visits for relationship testing $shortUrlWithVisits = ShortURL::factory() ->has(ShortURLVisit::factory()->count(5), 'visits') ->create(['track_visits' => true]); $this->assertCount(5, $shortUrlWithVisits->visits); $this->assertEquals('desktop', $shortUrlWithVisits->visits->first()->device_type); ``` -------------------------------- ### Generate Deterministic Key with `generateKeyUsing()` Source: https://context7.com/ash-jc-allen/short-url/llms.txt Use `generateKeyUsing()` to create a deterministic URL key from an integer seed. This is useful for generating reproducible keys tied to a known entity ID, ensuring the same seed always produces the same key format. ```php use AshAllenDesign\ShortURL\Classes\Builder; $productId = 9871; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/products/9871') ->generateKeyUsing($productId) ->make(); // Key is always the Hashids encoding of 9871 with configured salt/alphabet echo $shortURL->url_key; // e.g. "nY5kR" ``` -------------------------------- ### Configure Default URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Override the default base URL for short URLs by setting the 'default_url' in the config/short-url.php file. Set to null to use app.url. ```php 'default_url' => 'https://example.com', ``` -------------------------------- ### Forward Query Parameters with Builder Source: https://context7.com/ash-jc-allen/short-url/llms.txt Enables query parameters from the short URL to be appended to the destination URL during redirection. Incoming parameters are merged with existing ones. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURL = app(Builder::class) ->destinationUrl('https://shop.example.com/sale') ->forwardQueryParams() ->make(); // A visitor hitting: https://yourapp.com/short/Ab3Xy?utm_source=email&utm_medium=cpc // Gets redirected to: https://shop.example.com/sale?utm_source=email&utm_medium=cpc ``` -------------------------------- ### Enable Default Visit Tracking Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Set the default behavior for tracking visits on newly generated short URLs. This setting applies to future URLs and does not affect existing ones. ```php 'tracking' => [ 'default_enabled' => true, ... ] ``` -------------------------------- ### Generate Short URL Key Using Custom Seed Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Provide a custom integer seed to the `generateKeyUsing()` method to influence the generation of the short URL's key. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->generateKeyUsing(12345) ->make(); ``` -------------------------------- ### Configure Allowed URL Schemes Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Define the list of allowed URL schemes in the `short-url.php` config file to restrict or expand URL creation options. ```php 'allowed_url_schemes' => [ 'http://', 'https://', 'mailto://', 'myapp://', ], ``` -------------------------------- ### Forward Query Parameters in Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable forwarding of query parameters from the original request to the destination URL by setting `forward_query_params` to true or using the `->forwardQueryParams()` method. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('http://destination.com?param1=test') ->forwardQueryParams() ->make(); ``` -------------------------------- ### Builder::urlKey() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Explicitly sets the URL key instead of auto-generating one. The key is URL-encoded automatically and throws an exception if it already exists. ```APIDOC ## `Builder::urlKey()` — Set a custom key Explicitly sets the URL key instead of auto-generating one. The key is URL-encoded automatically. Throws `ShortURLException` if the key already exists in the database. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Exceptions\ShortURLException; try { $shortURL = app(Builder::class) ->destinationUrl('https://example.com/product/123') ->urlKey('product-123') ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/product-123 } catch (ShortURLException $e) { // Key already in use echo $e->getMessage(); // "A short URL with this key already exists." } ``` ``` -------------------------------- ### Builder::singleUse() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Marks the short URL as single-use. After the first visit, subsequent requests to the same key will result in an HTTP 404. ```APIDOC ## `Builder::singleUse()` — Create a one-time URL Marks the short URL as single-use; after the first visit, subsequent requests to the same key return HTTP 404. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/download/invoice-2024.pdf') ->singleUse() // disable after first visit ->redirectStatusCode(302) // use 302 so browsers don't cache ->make(); // First visit → redirects to destination, records visit // Second visit → HTTP 404 ``` ``` -------------------------------- ### Update KeyGenerator Constructor Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md The `KeyGenerator` constructor now requires a `Hashids` instance. Consider using `app(Hashids::class)` for container resolution. ```php use Hashids\Hashids; public function __construct(Hashids $hashids = null) ``` ```php use Hashids\Hashids; public function __construct(Hashids $hashids) ``` -------------------------------- ### Implement Custom UrlKeyGenerator Source: https://context7.com/ash-jc-allen/short-url/llms.txt Replace the default Hashids-based key generator by implementing the `UrlKeyGenerator` interface and binding it in the configuration. This allows for custom key generation logic. ```php namespace App\Services; use AshAllenDesign\ShortURL\Interfaces\UrlKeyGenerator; class NanoIdKeyGenerator implements UrlKeyGenerator { public function generateRandom(): string { // Use any custom key generation logic return substr(str_shuffle('abcdefghijklmnopqrstuvwxyz0123456789'), 0, 8); } public function generateKeyUsing(?int $seed = null): string { return ? base_convert((string) $seed, 10, 36) : $this->generateRandom(); } } ``` ```php 'url_key_generator' => \App\Services\NanoIdKeyGenerator::class, ``` -------------------------------- ### Find ShortURL by Key Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Retrieve a ShortURL model using its unique key with the `findByKey()` method. This is useful for direct lookups. ```php $shortURL = \AshAllenDesign\\ShortURL\\Models\\ShortURL::findByKey('abc123'); ``` -------------------------------- ### Configure Custom Model Factories Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Specify custom model factories for `ShortURL` and `ShortURLVisit` models within the `factories` config field if you are using your own factory implementations. ```php 'factories' => [ \AshAllenDesign\\ShortURL\\Models\\ShortURL::class => \AshAllenDesign\\ShortURL\\Models\\Factories\\ShortURLFactory::class, \AshAllenDesign\\ShortURL\\Models\\ShortURLVisit::class => \AshAllenDesign\\ShortURL\\Models\\Factories\\ShortURLVisitFactory::class ], ``` -------------------------------- ### Create Single Use Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Create a shortened URL that can only be visited once. Subsequent visits will result in a 404 error. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->singleUse() ->make(); ``` -------------------------------- ### Create ShortURL Model Factory Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Utilize the provided model factories for testing purposes. The `ShortURL` factory includes states like `deactivated` and `inactive` for creating specific scenarios. ```APIDOC ## Model Factories The package comes with model factories included for testing purposes. ```php use AshAllenDesign\ShortURL\Models\ShortURL; $shortUrl = ShortURL::factory()->create(); // URL is deactivated $deactivatedShortUrl = ShortURL::factory()->deactivated()->create(); // URL is neither activated nor deactivated $inactiveShortURL = ShortURL::factory()->inactive()->create(); ``` If you are using your own custom model factory, you can define the factories that the `ShortURL` and `ShortURLVisit` models should use by updating the `factories` config field: ```php 'factories' => [ \AshAllenDesign\ShortURL\Models\ShortURL::class => \AshAllenDesign\ShortURL\Models\Factories\ShortURLFactory::class, \AshAllenDesign\ShortURL\Models\ShortURLVisit::class => \AshAllenDesign\ShortURL\Models\Factories\ShortURLVisitFactory::class ], ``` ``` -------------------------------- ### Update Tracking Configuration in Laravel Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Add these lines to your `short-url.php` config file to enable tracking for referer URLs and device types. This is part of the v2.0.0 upgrade. ```php 'tracking' => [ ... 'fields' => [ ... 'referer_url' => true, 'device_type' => true, ], ], ``` -------------------------------- ### Set Activation and Deactivation Times for Short URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Define a specific active period for a short URL by setting both activation and deactivation times using `->activateAt()` and `->deactivateAt()` methods. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->activateAt("Carbon\Carbon"::now()->addDay()) ->deactivateAt("Carbon\Carbon"::now()->addDays(2)) ->make(); ``` -------------------------------- ### Generate a Shortened URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Use the `->make()` method to create a short URL. The `default_short_url` property on the returned model holds the generated URL. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->make(); $shortURL = $shortURLObject->default_short_url; ``` -------------------------------- ### Set Custom URL Key with Builder Source: https://context7.com/ash-jc-allen/short-url/llms.txt Explicitly sets a custom URL key. The key is automatically URL-encoded. A ShortURLException is thrown if the key already exists. ```php use AshAllenDesign\ShortURL\Classes\Builder; use AshAllenDesign\ShortURL\Exceptions\ShortURLException; try { $shortURL = app(Builder::class) ->destinationUrl('https://example.com/product/123') ->urlKey('product-123') ->make(); echo $shortURL->default_short_url; // https://yourapp.com/short/product-123 } catch (ShortURLException $e) { // Key already in use echo $e->getMessage(); // "A short URL with this key already exists." } ``` -------------------------------- ### Find ShortURLs by Destination URL Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Locate all ShortURL models that redirect to a specific destination URL using the `findByDestinationURL()` method. ```php $shortURLs = \AshAllenDesign\\ShortURL\\Models\\ShortURL::findByDestinationURL('https://destination.com'); ``` -------------------------------- ### Enable Browser Name Tracking Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Enable tracking of the visitor's browser name using the `->trackBrowser()` method. This method defaults to true if no argument is provided. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->trackVisits() ->trackBrowser() ->make(); ``` -------------------------------- ### Register Custom Short URL Routes Source: https://context7.com/ash-jc-allen/short-url/llms.txt Manually register short URL routes in your application's route file when the default route is disabled. You can use the facade helper for standard registration or define a fully custom route with your own middleware and prefixes. ```php // routes/web.php — Option A: use facade helper (respects config prefix & middleware) use AshAllenDesign\ShortURL\Facades\ShortURL; ShortURL::routes(); // routes/web.php — Option B: fully custom route with your own prefix use AshAllenDesign\ShortURL\Controllers\ShortURLController; Route::middleware(['web', 'throttle:60,1']) ->prefix('go') ->group(function () { Route::get('/{shortURLKey}', ShortURLController::class)->name('short-url.invoke'); }); // Disable default route in config when using custom route // config/short-url.php: 'disable_default_route' => true ``` -------------------------------- ### Update Resolver guessDeviceType Method Signature Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md The `guessDeviceType` method signature in the `Resolver` class has been updated to accept a `UserAgentDriver`. ```php protected function guessDeviceType(): string ``` ```php protected function guessDeviceType(UserAgentDriver $userAgentParser): ?string ``` -------------------------------- ### Manually Register Short URL Routes Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Manually register the default short URL routes in your application's routes file (e.g., web.php) by calling the ShortURL::routes() method. ```php \AshAllenDesign\ShortURL\Facades\ShortURL::routes(); ``` -------------------------------- ### Set Minimum URL Key Length Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Configure the minimum desired length for randomly generated URL keys. The actual key may be longer if all shorter keys are already in use. A minimum of 3 is enforced for performance. ```php 'key_length' => 10, ``` -------------------------------- ### Generate a Shortened URL with a Custom Key Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Assign a custom, meaningful key to a shortened URL using the `->urlKey()` method. Ensure the key is unique, as duplicate keys are not permitted. ```php use AshAllenDesign\ShortURL\Classes\Builder; $shortURLObject = app(Builder::class) ->destinationUrl('https://destination.com') ->urlKey('custom-key') ->make(); $shortURL = $shortURLObject->default_short_url; // Short URL: https://webapp.com/short/custom-key ``` -------------------------------- ### Builder::generateKeyUsing() Source: https://context7.com/ash-jc-allen/short-url/llms.txt Generates a deterministic key from an integer seed using Hashids. This is useful for creating reproducible keys tied to a known entity ID. ```APIDOC ## `Builder::generateKeyUsing()` — Deterministic key from seed Passes an integer seed directly to Hashids to produce a deterministic (but still unique-format) key. Useful for generating reproducible keys tied to a known entity ID. ```php use AshAllenDesign\ShortURL\Classes\Builder; $productId = 9871; $shortURL = app(Builder::class) ->destinationUrl('https://example.com/products/9871') ->generateKeyUsing($productId) ->make(); // Key is always the Hashids encoding of 9871 with configured salt/alphabet echo $shortURL->url_key; // e.g. "nY5kR" ``` ``` -------------------------------- ### Define Middleware for Default Route Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Apply custom middleware or middleware groups to the default short URL route by configuring the 'middleware' option. This does not apply to custom routes. ```php 'middleware' => [ MyAwesomeMiddleware::class, ], ``` ```php 'middleware' => [ 'web', ], ``` -------------------------------- ### Access ShortURLVisit Records and Device Constants Source: https://context7.com/ash-jc-allen/short-url/llms.txt Query the ShortURLVisit model to retrieve analytics data for each visit. Use device type constants for filtering and navigate back to the associated ShortURL using the `shortURL` relationship. ```php use AshAllenDesign\ShortURL\Models\ShortURLVisit; // Device type constants ShortURLVisit::DEVICE_TYPE_DESKTOP; // 'desktop' ShortURLVisit::DEVICE_TYPE_MOBILE; // 'mobile' ShortURLVisit::DEVICE_TYPE_TABLET; // 'tablet' ShortURLVisit::DEVICE_TYPE_ROBOT; // 'robot' // Query visits and navigate back to the parent ShortURL $mobileVisits = ShortURLVisit::where('device_type', ShortURLVisit::DEVICE_TYPE_MOBILE) ->with('shortURL') ->latest('visited_at') ->get(); foreach ($mobileVisits as $visit) { echo $visit->ip_address; // '203.0.113.42' echo $visit->browser; // 'Chrome' echo $visit->browser_version; // '120.0' echo $visit->operating_system; // 'Android' echo $visit->operating_system_version; // '14.0' echo $visit->referer_url; // 'https://twitter.com/...' echo $visit->visited_at; // Carbon datetime echo $visit->shortURL->url_key; // related ShortURL } ``` -------------------------------- ### Configure Allowed URL Schemes Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md By default, Short URL allows 'http://' and 'https://'. You can customize this list in your `short-url.php` config file to include or exclude schemes like 'mailto://' or custom ones. ```APIDOC ## Configuration ### Allowed URL Schemes To change the list of allowed URL schemes, you can define the list using the `allowed_url_schemes` field in your `short-url.php` config file. ```php 'allowed_url_schemes' => [ 'http://', 'https://', 'mailto://', 'myapp://', ], ``` ``` -------------------------------- ### Add Custom Short URL Route Source: https://github.com/ash-jc-allen/short-url/blob/master/README.md Add a custom web route to your web.php file to handle shortened URLs using the {shortURLKey} parameter. ```php Route::get('/custom/{shortURLKey}', '\AshAllenDesign\ShortURL\Controllers\ShortURLController'); ``` -------------------------------- ### Enable Configuration Validation in Laravel Source: https://github.com/ash-jc-allen/short-url/blob/master/UPGRADE.md Add this line to your `short-url.php` config file to re-enable configuration validation, which is disabled by default in newer versions. ```php 'validate_config' => true, ```