URL shorteners in Laravel are a very practical solution when you need to share long links, control access, or simply avoid visually overloading an interface, an email, or a post. In my case, having the ability to generate short URLs directly from my own Laravel application has always given me a huge advantage over depending on external services.
In this article, I explain how to create a URL shortener in Laravel using Ash Allen's Short URL package, from installation to its most advanced features, with real examples and common use cases in production projects.
What is a URL shortener in Laravel and when to use it
What is Short URL and why use a package instead of building it from scratch
Short URL (ashallendesign/short-url) is an open-source package for Laravel that allows you to generate short URLs quickly and in a controlled manner. Instead of reinventing the wheel by manually creating tables, controllers, and redirection logic, this package offers you a solid, maintained, and well-integrated solution within the Laravel ecosystem.
It covers practically all real-world cases that usually appear in an application:
- tracking
- access control
- activation dates
- single-use URLs
- everything without complications
Real cases where a shortener in Laravel makes a difference
Some scenarios where it makes a lot of sense to use a URL shortener within Laravel:
- Temporary links for marketing campaigns
- Cleaner URLs for emails or notifications
- Unique access for downloads or invitations
- Basic tracking without depending on external tools
- Greater control and privacy over data
Installing the Short URL package in Laravel
Minimum requirements
Before installing the package, make sure you meet these requirements:
- Laravel 8.0 or higher
- PHP 8.0 or higher
Installation with Composer
Installation is straightforward using Composer:
$ composer require ashallendesign/short-urlPublishing configuration and migrations
After installing it, publish the configuration file and the migrations:
$ php artisan vendor:publish --provider="AshAllenDesign\ShortURL\Providers\ShortURLProvider"The package adds two new tables to the database:
- short_urls
- short_url_visits
Run the migrations:
$ php artisan migrateWith this, the URL shortener is ready to use.
How to create short URLs in Laravel with Short URL
Create a basic short URL
The fastest way to generate a short URL is to specify the destination URL and call the make() method:
use AshAllenDesign\ShortURL\Facades\ShortURL;
$shortURLObject = ShortURL::destinationUrl('https://destination.com')->make();
$shortURL = $shortURLObject->default_short_url;It is up to you to configure and create short URLs around your existing data; for example, you could generate a short URL when a new post model is published.
This automatically creates a record in the database and returns the generated short URL.
Obtaining and using the generated URL in your application
The default_short_url property is the one you will normally use to display or share the link. This approach fits very well when you generate short URLs upon creating a model, such as a post or a campaign.
- Custom URL keys
- Single-use short URLs
- Enforce HTTPS
- Configure the redirect status code (302 found instead of 301 permanent)
- Make a short URL active and inactive on a specific date
- Visitor tracking:
- IP address
- Browser name
- Browser version
- Operating system name
- Operating system version
- Referer URL (the URL the visitor originally came from)
- Device type (can be: desktop / mobile / tablet / robot)
Below are more examples of how to work with existing ShortURL model instances from the README:
use \AshAllenDesign\ShortURL\Models\ShortURL;
// Find URL by key
$shortURL = ShortURL::findByKey('abc123');
// Find by destination
$shortURLs = ShortURL::findByDestinationURL('https://destination.com');
// Enable tracking to an existing short URL instance
$shortURL->trackingEnabled();
// Get model properties, such as visits
$shortURL = ShortURL::find(1);
$visits = $shortURL->visits;
// Single-use short URL
$builder = new \AshAllenDesign\ShortURL\Classes\Builder();
$shortURLObject = $builder
->destinationUrl('https://destination.com')
->singleUse()
->make();Using custom keys in short URLs
What is a urlKey and what is it for
By default, Short URL generates a random key at the end of the link, something like:
https://webapp.com/short/abc123But often it is interesting to use more descriptive keys, especially in campaigns or public links.
Example with custom keys
You can define a custom key using urlKey():
use AshAllenDesign\ShortURL\Facades\ShortURL;
$shortUrl = ShortURL::destinationUrl('https://destination.com')
->urlKey('custom-key')
->make()
->default_short_url;
// Result: https://webapp.com/short/custom-keyThis small detail greatly improves readability and user trust.
Tracking visits on short URLs
What data can be tracked
One of the great advantages of the package is the integrated tracking. By default, it can record:
- IP address
- Browser and version
- Operating system and version
- Referer URL
- Device type (desktop, mobile, tablet, robot)
When I have needed quick statistics without setting up Google Analytics, this functionality has been more than enough.
Enable or disable visit tracking
Tracking is enabled by default, but you can force it when creating the URL:
$shortURLObject = ShortURL::destinationUrl('https://destination.com') ->trackVisits() ->make();Or explicitly disable it:
$shortURLObject = ShortURL::destinationUrl('https://destination.com') ->trackVisits(false) ->make();Enable or exclude specific tracking fields
You can also decide exactly what data is saved:
ShortURL::destinationUrl('https://destination.com')
->trackVisits()
->trackIPAddress()
->trackBrowser()
->trackBrowserVersion()
->trackOperatingSystem()
->trackOperatingSystemVersion()
->trackDeviceType()
->trackRefererURL()
->make();Or exclude a specific one, for example the IP:
ShortURL::destinationUrl('https://destination.com')
->trackVisits()
->trackIPAddress(false)
->make();Single-use short URLs and access control
When it makes sense to use single-use URLs
Single-use URLs are very useful for:
- Private invitations
- One-time downloads
- Sensitive access
Once visited, they automatically return a 404.
Create short URLs that can only be visited once:
ShortURL::destinationUrl('https://destination.com')->singleUse()->make();Activation and deactivation of URLs by dates
Example with activation and expiration dates
Activate a URL tomorrow:
ShortURL::activateAt(now()->addDay())->make();Activate it tomorrow and deactivate it the day after tomorrow:
ShortURL::activateAt(now()->addDay())->deactivateAt(now()->addDays(2))->make();If someone tries to access outside of that range, they will receive a 404.
Customization of routes and short URL prefix
Default route /short/{key}
The package includes a ready-to-use route:
/short/{shortURLKey}How to change the prefix of short URLs
If you want to change /short to something shorter like /s, you can do so from the short-url.php configuration file by modifying the prefix field.
Working with the ShortURL model and statistics
Find URLs by key or destination
The ShortURL model extends Eloquent, so you can work with it easily:
use AshAllenDesign\ShortURL\Models\ShortURL;
$shortURL = ShortURL::findByKey('abc123');
$shortURLs = ShortURL::findByDestinationURL('https://destination.com');Access visits and metrics from Eloquent
$shortURL = ShortURL::find(1);
$visits = $shortURL->visits;This part is especially useful if you want to build your own internal reports or dashboards.
Advantages over external services
- Total data control
- No external dependencies
- Direct integration with your business logic
- More privacy for your users
Performance, control, and privacy
Having the shortener within Laravel allows you to optimize performance and adapt behavior exactly to your needs, something that is not always possible with external services.
Frequently asked questions about URL shorteners in Laravel
- Is Short URL free?
- Yes, it is an open-source package.
- Can temporary URLs be created in Laravel?
- Yes, using activation and deactivation dates.
- Where are visits stored?
- In the short_url_visits table.
- Can the default route be changed?
- Yes, from the configuration file.
Conclusion
Implementing URL shorteners in Laravel with the Short URL package is a powerful, flexible, and easy-to-maintain solution. In my experience, it covers practically all real-world scenarios without adding unnecessary complexity to the project. If you need controlled short URLs, with tracking and fully integrated into Laravel, this package is a safe bet.
I agree to receive announcements of interest about this Blog.
Learn how to create a URL shortener in Laravel using the Short URL package. Complete guide on installation, visitor tracking, custom keys, and one-time links.