https://ashallendesign.ams3.digitaloceanspaces.com/public/blog/56/how-to-create-short-urls-in-laravel.png
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.
There’s also a really useful, quick review video by Povilas Korop (Laravel Daily) at the end of this article to show how you can use the package.
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:
1use AshAllenDesign\ShortURL\Facades\ShortURL;
2
3$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).
In fact, if you read my monthly Round Up articles (such as “Round Up: March 2022“), you’ll likely know that I’m using Short URL as the basis for building a small privact-first, open source URL shortening service. The service is called Mango Two and is something that I’m slowly building as a side project so that I can have some practice with using Typescript to build a Chrome extension. If you’re interested in checking it out, there’s already an early version of the extension available for installing that you can install in under 30 seconds! Any feedback on the Mango Two Chrome extension is greatly appreciated.
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:
1composer 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:
1php 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:
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.
1use AshAllenDesign\ShortURL\Facades\ShortURL;
2
3$shortURLObject = ShortURL::destinationUrl('https://destination.com')->make();
4
5$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:
1use AshAllenDesign\ShortURL\Facades\ShortURL;
2
3$shortUrl = ShortURL::destinationUrl('https://destination.com')
4 ->urlKey('custom-key')
5 ->make()
6 ->default_short_url;
7
8// $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:
1$shortURLObject = ShortURL::destinationUrl('https://destination.com')
2 ->trackVisits()
3 ->make();
Likewise, if we wanted to force tracking to be disabled for the URL, our code might look something like this:
1$shortURLObject = ShortURL::destinationUrl('https://destination.com')
2 ->trackVisits(false)
3 ->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:
1ShortURL::destinationUrl('https://destination.com')
2 ->trackVisits()
3 ->trackIPAddress()
4 ->trackBrowser()
5 ->trackBrowserVersion()
6 ->trackOperatingSystem()
7 ->trackOperatingSystemVersion()
8 ->trackDeviceType()
9 ->trackRefererURL()
10 ->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:
1ShortURL::destinationUrl('https://destination.com')
2 ->trackVisits()
3 ->trackIPAddress(false)
4 ->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:
1ShortURL::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:
1ShortURL::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:
1ShortURL::activateAt(now()->addDay())
2 ->deactivateAt(now()->addDays(2))
3 ->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:
config/short-url.php
1return [
2
3 // ...
4
5 'prefix' => 's',
6
7 // ...
8
9];
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:
config/short-url.php
1return [
2
3 // ...
4
5 'prefix' => null,
6
7 // ...
8
9];
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:
web.php
1Route::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:
config/short-url.php
1return [
2
3 // ...
4
5 'disable_default_route' => true,
6
7 // ...
8
9];
Laravel Daily Review
Povilas Korop also made a quick review video of the Short URL package. So, you can see it in action here:
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 below.
Keep on building awesome stuff! 🚀
Laravel News Links