PHPackages                             batnieluyo/short-url - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. batnieluyo/short-url

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

batnieluyo/short-url
====================

A Laravel package for creating shortened URLs for your web apps.

0.1.0(2y ago)09MITPHPPHP ^8.0

Since Feb 13Pushed 2y agoCompare

[ Source](https://github.com/batnieluyo/short-url)[ Packagist](https://packagist.org/packages/batnieluyo/short-url)[ Docs](https://github.com/batnieluyo/short-url)[ GitHub Sponsors](https://github.com/ash-jc-allen)[ RSS](/packages/batnieluyo-short-url/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (9)Versions (2)Used By (0)

[![](https://camo.githubusercontent.com/f0a648b5b6677dd3b6b70465651c28d0515d98120df9f6459a6d3902a34a3603/68747470733a2f2f617368616c6c656e64657369676e2e636f2e756b2f696d616765732f637573746f6d2f73686f72742d75726c2d6c6f676f2e706e67)](https://camo.githubusercontent.com/f0a648b5b6677dd3b6b70465651c28d0515d98120df9f6459a6d3902a34a3603/68747470733a2f2f617368616c6c656e64657369676e2e636f2e756b2f696d616765732f637573746f6d2f73686f72742d75726c2d6c6f676f2e706e67)

[![Latest Version on Packagist](https://camo.githubusercontent.com/afb14357e4b9ba1dd1bd44cebe2b5862f120521d2cc7286ecd87f8f3b4f8ab75/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f617368616c6c656e64657369676e2f73686f72742d75726c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ashallendesign/short-url)[![Total Downloads](https://camo.githubusercontent.com/acf6d134dfdf33ccea474447226f0579bf13038d2b38ec40294d0c2a18f573dc/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f617368616c6c656e64657369676e2f73686f72742d75726c2e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ashallendesign/short-url)[![PHP from Packagist](https://camo.githubusercontent.com/3cd51f0e77b948048ba7f6fd58f0a6441c9bf82c839bf2d66d0ce31f72321f10/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f617368616c6c656e64657369676e2f73686f72742d75726c3f7374796c653d666c61742d737175617265)](https://packagist.org/packages/ashallendesign/short-url)[![GitHub license](https://camo.githubusercontent.com/cfe5353b361b8b8cbc793ee149b736b20c678a9535e3f6ccd6a32b1868aee18a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f6173682d6a632d616c6c656e2f73686f72742d75726c3f7374796c653d666c61742d737175617265)](https://github.com/ash-jc-allen/short-url/blob/master/LICENSE)

Table of Contents
-----------------

[](#table-of-contents)

- [Overview](#overview)
- [Installation](#installation)
    - [Requirements](#requirements)
    - [Install the Package](#install-the-package)
    - [Publish the Config and Migrations](#publish-the-config-and-migrations)
    - [Migrate the Database](#migrate-the-database)
- [Usage](#usage)
    - [Building Shortened URLs](#building-shortened-urls)
        - [Quick Start](#quick-start)
        - [Custom Keys](#custom-keys)
        - [Tracking Visitors](#tracking-visitors)
            - [Enabling Tracking](#enabling-tracking)
            - [Tracking IP Address](#tracking-ip-address)
            - [Tracking Browser &amp; Browser Version](#tracking-browser--browser-version)
            - [Tracking Operating System &amp; Operating System Version](#tracking-operating-system--operating-system-version)
            - [Tracking Device Type](#tracking-device-type)
            - [Tracking Referer URL](#tracking-referer-url)
        - [Custom Short URL Fields](#custom-short-url-fields)
        - [Single Use](#single-use)
        - [Enforce HTTPS](#enforce-https)
        - [Forwarding Query Parameters](#forwarding-query-parameters)
        - [Redirect Status Code](#redirect-status-code)
        - [Activation and Deactivation Times](#activation-and-deactivation-times)
        - [Using a Custom Seed](#using-a-custom-seed)
        - [Facade](#facade)
        - [Conditionals](#conditionals)
    - [Using the Shortened URLs](#using-the-shortened-urls)
        - [Default Route and Controller](#default-route-and-controller)
        - [Custom Route](#custom-route)
    - [Tracking](#tracking)
    - [Customisation](#customisation)
        - [Disabling the Default Route](#disabling-the-default-route)
        - [Default URL Key Length](#default-url-key-length)
        - [Tracking Visits](#tracking-visits)
            - [Default Tracking](#default-tracking)
            - [Tracking Fields](#tracking-fields)
        - [Config Validation](#config-validation)
        - [Custom Database Connection](#custom-database-connection)
    - [Helper Methods](#helper-methods)
        - [Visits](#visits)
        - [Find by URL Key](#find-by-url-key)
        - [Find by Destination URL](#find-by-destination-url)
        - [Tracking Enabled](#tracking-enabled)
        - [Tracked Fields](#tracked-fields)
    - [Events](#events)
        - [Short URL Visited](#short-url-visited)
    - [Model Factories](#model-factories)
- [Testing](#testing)
- [Security](#security)
- [Contribution](#contribution)
- [Credits](#credits)
- [Changelog](#changelog)
- [Upgrading](#upgrading)
- [License](#license)

Overview
--------

[](#overview)

A Laravel package that can be used for adding shortened URLs to your existing web app.

Installation
------------

[](#installation)

### Requirements

[](#requirements)

The package has been developed and tested to work with the following minimum requirements:

- PHP 8.0
- Laravel 10

Short URL requires either the [BC Math](https://secure.php.net/manual/en/book.bc.php) or [GMP](https://secure.php.net/manual/en/book.gmp.php) PHP extensions in order to work.

### Install the Package

[](#install-the-package)

You can install the package via Composer:

```
composer require batnieluyo/short-url
```

### Publish the Config and Migrations

[](#publish-the-config-and-migrations)

You can then publish the package's config file and database migrations by using the following command:

```
php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider"
```

### Migrate the Database

[](#migrate-the-database)

This package contains two migrations that add two new tables to the database: `short_urls` and `short_url_visits`. To run these migrations, simply run the following command:

```
php artisan migrate
```

Usage
-----

[](#usage)

### Building Shortened URLs

[](#building-shortened-urls)

#### Quick Start

[](#quick-start)

The quickest way to get started with creating a shortened URL is by using the snippet below. The `->make()` method returns a ShortURL model that you can grab the shortened URL from.

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->make();
$shortURL = $shortURLObject->default_short_url;
```

#### Custom Keys

[](#custom-keys)

By default, the shortened URL that is generated will contain a random key. The key will be of the length that you define in the config files (defaults to 5 characters). Example: if a URL is `https://webapp.com/short/abc123`, the key is `abc123`.

You may wish to define a custom key yourself for that URL that is more meaningful than a randomly generated one. You can do this by using the `->urlKey()` method. Example:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->urlKey('custom-key')->make();
$shortURL = $shortURLObject->default_short_url;

// Short URL: https://webapp.com/short/custom-key
```

Note: All of the URL keys are unique, so you cannot use a key that already exists in the database for another shortened URL.

#### Tracking Visitors

[](#tracking-visitors)

You may want to track some data about the visitors that have used the shortened URL. This can be useful for analytics. By default, tracking is enabled and all of the available tracking fields are also enabled. You can toggle the default options for the different parts of the tracking in the config file. Read further on in the [Customisation](#customisation)section to see how to customise the default tracking behaviours.

Note: Even if the tracking options (such as `track_ip_address`) are enabled for a short URL, they won't be recorded unless the `track_visits` options is enabled. This can come in handy if you want to enable/disable tracking for a short URL without needing to individually set each option.

##### Enabling Tracking

[](#enabling-tracking)

If you want to override whether if tracking is enabled or not when creating a shortened URL, you can use the `->trackVisits()` method. This method accepts a boolean but defaults to `true` if a parameter is not passed.

The example below shows how to enable tracking for the URL and override the config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->make();
```

The example below shows how to disable tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits(false)->make();
```

##### Tracking IP Address

[](#tracking-ip-address)

If you want to override whether if IP address tracking is enabled or not when creating a shortened URL, you can use the `->trackIPAddress()` method. This method accepts a boolean but defaults to `true` if a parameter is not passed.

The example below shows how to enable IP address tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackIPAddress()->make();
```

##### Tracking Browser &amp; Browser Version

[](#tracking-browser--browser-version)

If you want to override whether if browser name and browser version tracking is enabled or not when creating a shortened URL, you can use the `->trackBrowser()` and `->trackBrowserVersion()` methods. This method accepts a boolean but defaults to `true` if a parameter is not passed.

The example below shows how to enable browser name tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackBrowser()->make();
```

The example below shows how to enable browser version tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackBrowserVersion()->make();
```

##### Tracking Operating System &amp; Operating System Version

[](#tracking-operating-system--operating-system-version)

If you want to override whether if operating system name and operating system version tracking is enabled or not when creating a shortened URL, you can use the `->trackOperatingSystem()` and `->trackOperatingSystemVersion()`methods. These methods accept a boolean but default to `true` if a parameter is not passed.

The example below shows how to enable operating system name tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackOperatingSystem()->make();
```

The example below shows how to enable operating system version tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackOperatingSystemVersion()->make();
```

##### Tracking Device Type

[](#tracking-device-type)

If you want to override whether if device type tracking is enabled or not when creating a shortened URL, you can use the `->trackDeviceType()` method. This method accepts a boolean but defaults to `true` if a parameter is not passed.

The example below shows how to enable device type tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackDeviceType()->make();
```

##### Tracking Referer URL

[](#tracking-referer-url)

If you want to override whether if referer URL tracking is enabled or not when creating a shortened URL, you can use the `->trackRefererURL()` method. This method accepts a boolean but defaults to `true` if a parameter is not passed.

The example below shows how to enable referer URL tracking for the URL and override the default config variable:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->trackVisits()->trackRefererURL()->make();
```

#### Custom Short URL Fields

[](#custom-short-url-fields)

There may be times when you want to add your own custom fields to the ShortURL model and store them in the database. For example, you might want to associate the short URL with a tenant, organisation, user, etc.

To do this you can use the `beforeCreate` method when building your short URL. This method accepts a closure that receives the `AshAllenDesign\ShortURL\Models\ShortURL` model instance before it's saved to your database.

The example below shows how to add a `tenant_id` field to the `AshAllenDesign\ShortURL\Models\ShortURL` model:

```
use AshAllenDesign\ShortURL\Models\ShortURL;
use AshAllenDesign\ShortURL\Facades\ShortURL as ShortUrlBuilder;

$tenantId = 123;

$shortURL = ShortUrlBuilder::destinationUrl($url)
    ->beforeCreate(function (ShortURL $model): void {
        $model->tenant_id = $tenantId;
    })
    ->make();
```

Please remember that to store custom fields in the database, you'll have to make sure those fields are added to the `short_urls` table. You can do this by creating a new migration that adds the fields to the table, or by updating the migrations that ship with this package.

#### Single Use

[](#single-use)

By default, all of the shortened URLs can be visited for as long as you leave them available. However, you may want to only allow access to a shortened URL once. Then any visitors who visit the URL after it has already been viewed will get a HTTP 404.

To create a single use shortened URL, you can use the `->singleUse()` method.

The example below shows how to create a single use shortened URL:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')->singleUse()->make();
```

#### Enforce HTTPS

[](#enforce-https)

When building a shortened URL, you might want to enforce that the visitor is redirected to the HTTPS version of the destination URL. This can be particularly useful if you're allowing your web app users to create their own shortened URLS.

To enforce HTTPS, you can use the `->secure()` method when building the shortened URL.

The example below shows how to create a secure shortened URL:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('http://destination.com')->secure()->make();

// Destination URL: https://destination.com
```

#### Forwarding Query Parameters

[](#forwarding-query-parameters)

When building a short URL, you might want to forward the query parameters sent in the request to destination URL. By default, this functionality is disabled, but can be enabled by setting the `forward_query_params` config option to `true`.

Alternatively, you can also use the `->forwardQueryParams()` method when building your shortened URL, as shown in the example below:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('http://destination.com?param1=test')->forwardQueryParams()->make();
```

Based on the example above, assuming that the original short URL's `destination_url` was `https://destination.com`, making a request to `https://webapp.com/short/xxx?param1=abc&param2=def` would redirect to `https://destination.com?param1=test&param2=def`

#### Redirect Status Code

[](#redirect-status-code)

By default, all short URLs are redirected with a `301` HTTP status code. But, this can be overridden when building the shortened URL using the `->redirectStatusCode()` method.

The example below shows how to create a shortened URL with a redirect HTTP status code of `302`:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('http://destination.com')->redirectStatusCode(302)->make();
```

#### Activation and Deactivation Times

[](#activation-and-deactivation-times)

By default, all short URLs that you create are active until you delete them. However, you may set activation and deactivation times for your URLs when you're creating them.

Doing this can be useful for marketing campaigns. For example, you may want to launch a new URL for a marketing campaign on a given date and then automatically deactivate that URL when the marketing campaign comes to an end.

The example below shows how to create a shortened URL that will be active from this time tomorrow onwards:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->activateAt(\Carbon\Carbon::now()->addDay())->make();
```

The example below shows how to create a shortened URL that will be active from this time tomorrow onwards and then is deactivated the day after:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->activateAt(\Carbon\Carbon::now()->addDay())
                          ->deactivateAt(\Carbon\Carbon::now()->addDays(2))
                          ->make();
```

#### Using a Custom Seed

[](#using-a-custom-seed)

By default, the package will use the ID of the last inserted short URL as the seed for generating a short URL's key. In some cases, you may want to use a custom seed instead. To do this, you can pass an integer to the `generateKeyUsing` method like so:

```
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();

$shortURLObject = $builder->destinationUrl('https://destination.com')
   ->generateKeyUsing(12345)
   ->make();
```

#### Facade

[](#facade)

If you prefer to use facades in Laravel, you can choose to use the provided `ShortURL` facade instead of instantiating the `Builder` class manually.

The example below shows an example of how you could use the facade to create a shortened URL:

```
