Support the ongoing development of Laravel.io →
Article Hero Image

How to Create Short URLs in Laravel

8 Jun, 2022 9 min read

Photo by Jesse Bowser on Unsplash

Introduction

Short URL is an open-source Laravel package that you can use to create short URLs for your web apps. It comes with different options for tracking users that click your short URL and it only takes a couple of minutes to add it to your Laravel project.

In this article, we're going to step through how to install Short URL (ashallendesign/short-url) in your Laravel projects and then take a look at a few of the different customisation options that are available. If you're interested in checking out the code for the package and seeing what other functionality the package provides, you can view it in the GitHub repository.

To get a better idea of what the package does, let's take a quick look at a basic example. Imagine that you have a Laravel app hosted on https://my-web-app.com and you want to create a short URL to redirect the user to https://ashallendesign.co.uk. To do this, your code might look something like this:

use AshAllenDesign\ShortURL\Facades\ShortURL;

$shortUrl = ShortURL::destinationUrl('https://ashallendesign.co.uk')->make();

We can then imagine that this code would create a short URL similar to this: http://my-web-app.com/short/abc123. Now, if you were to navigate to this URL, you'd be redirected to https://ashallendesign.co.uk and your visit would be recorded in the database (if the tracking features are enabled).

Installing the Package

To get started with the Short URL package, you'll need to make sure that your Laravel app is using at least Laravel 8.0 and PHP 8.0.

You can install the package via Composer using the following command:

composer require ashallendesign/short-url

After installing the package, 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"

This package contains several 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

Congratulations, Short URL should now be installed in your Laravel app and ready to use!

Creating Short URLs

Now that we've installed Short URL, let's take a look at how we can create our own short URLs.

The quickest way would be to use something similar to the snippet below. We simply need to choose the destination URL that the visitors would be redirected to, and then use the make method to store the Short URL in database.

use AshAllenDesign\ShortURL\Facades\ShortURL;

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

$shortURL = $shortURLObject->default_short_url;

The make method returns a AshAllenDesign\ShortURL\Models\ShortURL model that extends the default Laravel Illuminate\Database\Eloquent\Model class. So, all of the usual methods that you'd typically call on your Laravel models can also be used here if you'd like.

Using Custom Short URL Keys

By default, the shortened URL that is generated will contain a random key (the key is the unique identifier that is placed at the end of short URLs). For example, if a short URL is https://webapp.com/short/abc123, the key would be abc123.

Sometimes, you may wish to define a custom key yourself for that URL that is more meaningful to your visitors than a randomly generated one. This is perfect for if you're using the short URLs for things like marketing or advertising campaigns.

To define a custom short URL key, you use the urlKey() method, like in the example below:

use AshAllenDesign\ShortURL\Facades\ShortURL;

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

// $shortUrl will be equal to: "https://webapp.com/short/custom-key"

Tracking Visitors

Depending on what you're using the short URLs for, you may want to track some data about the visitors that have used the short URL. This can be particularly 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 package's short-url.php config file that you published when installing the package.

If you want to override the default option set in the config file whether tracking is enabled or not when creating a shortened URL, you can use the trackVisits() method.

For example, if we wanted to force tracking to be enabled for the URL, our code might look something like this:

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

Likewise, if we wanted to force tracking to be disabled for the URL, our code might look something like this:

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

Enabling Tracking Fields

If tracking is enabled for a shortened URL, each time the link is visited, a new ShortURLVisit row in the database will be created. By default, the package will record the following fields of a visitor:

  • IP Address
  • Browser Name
  • Browser Version
  • Operating System Name
  • Operating System Version
  • Referer URL (the URL that the visitor originally came from)
  • Device Type (can be: desktop/mobile/tablet/robot)

Each of these fields can be toggled in the config files so that you only record the fields you need. However, if you want to override any of the default options, you can do so when creating your short URL.

For example, if we wanted to force all of the tracking fields to be enabled when creating our short URLs, our code might look something like this:

ShortURL::destinationUrl('https://destination.com')
    ->trackVisits()
    ->trackIPAddress()
    ->trackBrowser()
    ->trackBrowserVersion()
    ->trackOperatingSystem()
    ->trackOperatingSystemVersion()
    ->trackDeviceType()
    ->trackRefererURL()
    ->make();

It's worth noting that each of the tracking methods also allows you to pass false as the argument to force a specific fields to not be tracked. For example, if we wanted to force the IP address to not be tracked, our code could look something like so:

ShortURL::destinationUrl('https://destination.com')
    ->trackVisits()
    ->trackIPAddress(false)
    ->make();

Creating Single-use Short URLs

By default, all of the short URLs that you create can be visited for as long as you leave them available in your database. However, depending on how you're using them in your applications, you may want to only allow access to a short URL once. This would then mean that any subsequent visitors who visit the URL after it has already been viewed will get a HTTP 404 response.

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:

ShortURL::destinationUrl('https://destination.com')->singleUse()->make();

Setting Activation and Deactivation Times

By default, all short URLs that you create are active and accessible as soon as you create them and until you delete them from your database. However, the package provides functionality for you to set activation and deactivation times for your URLs when you're creating them.

Doing this can be useful for things like marketing or advertising 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 campaign comes to an end.

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

ShortURL::activateAt(now()->addDay())->make();

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

ShortURL::activateAt(now()->addDay())
    ->deactivateAt(now()->addDays(2))
    ->make();

If a user was to visit a short URL before it was activated or after it was deactivated, they would receive a HTTP 404 response.

Customising the Short URL Prefix

The Short URL package comes with a route that you can use for your short URLs without any further setup. By default, this route is /short/{shortURLKey}.

You might want to keep using this default route but change the /short/ prefix to something else. To do this, you can change the prefix field in the config.

For example, if we wanted to change the default short URL to /s, we could change the config value like so:

return [

    // ...
  
    'prefix' => 's',

    // ...

];

Likewise, you may also remove the prefix from the default route completely. For example, if you want your short URL to be accessible via /{shortUrlKey}, then we could update the prefix config value to null like so:

return [

    // ...
  
    'prefix' => null,

    // ...

];

Using the Short URLs

Now that we know how to create the short URLs, let's take a look at how to visit them in our applications.

The package makes using the short URLs super simple because it ships with it's own route and controller that are automatically available without any set up.

Unless you changed the prefix field in the short-url.php config file, the package's route is available at short/{urlKey}. This route uses the single-use controller that is found at \AshAllenDesign\ShortURL\Controllers\ShortURLController.

That's it, there's nothing more to it (as long as you want to use the package's route)! You can start sharing your short URLs and they can be instantly accessed by your visitors.

Using a Custom Route

There may be times when you wish to use your own route or controller for your short URLs other than the default URLs that are created.

If you want to use a different route but use the same controller, you'll just need to add your new route to your web.php field and point it to the controller like so:

Route::get('/custom/{shortURLKey}', '\AshAllenDesign\ShortURL\Controllers\ShortURLController');

It's important to remember that your route must include a {shortURLKey} field.

If you do choose to use your own route or controller, you might want to disable the default route that the app provides. By doing this, any visitors who try to use the packages default route (when you don't want them to), will receive a HTTP 404 response. To do disable the route, you can set the disable_default_route field in your short-url.php config file to true, like so:

return [

    // ...
  
    'disable_default_route' => true,

    // ...

];

Conclusion

Hopefully, this post should have shown you how you can use the Short URL package in your Laravel apps to create shortened URLs. If you're interested in checking out the code for the Short URL package, you can view it in the GitHub repo.

If you enjoyed reading this post, I'd love to hear about it. Likewise, if you have any feedback to improve the future ones, I'd also love to hear that too.

If you're interested in getting updated each time I publish a new post, feel free to sign up for my newsletter.

Keep on building awesome stuff! 🚀

Last updated 3 weeks ago.

driesvints, waelkhalifa, alecgarcia, ash-jc-allen, felixramowda, zaki liked this article

6
Like this article? Let the author know and give them a clap!
ash-jc-allen (Ash Allen) I'm a freelance Laravel web developer from Preston, UK. I maintain the Ash Allen Design blog and get to work on loads of cool and exciting projects 🚀

Other articles you might like

Article Hero Image November 18th 2024

Laravel Custom Query Builders Over Scopes

Hello 👋 Alright, let's talk about Query Scopes. They're awesome, they make queries much easier to r...

Read article
Article Hero Image November 19th 2024

Access Laravel before and after running Pest tests

How to access the Laravel ecosystem by simulating the beforeAll and afterAll methods in a Pest test....

Read article
Article Hero Image November 11th 2024

🍣 Sushi — Your Eloquent model driver for other data sources

In Laravel projects, we usually store data in databases, create tables, and run migrations. But not...

Read article

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.