You are probably already familiar with URL shortening services like or Short URLs are simple to remember and will make it much easier to distribute these URLs. So, in this article, I'll explain how to create a URL shortener in Laravel 8 using the URL shortener package.

In this tutorial, I'll be using Ash Allen's Short URL package, which includes features like a custom URL key, visitor tracking, activation and deactivation times, among others.

Table of Contents

  1. Install Laravel
  2. Install Laravel URL Shortener Package
  3. Setup Database
  4. Define Route & Logic
  5. Setup View
  6. Testing 1
  7. Custom Route
  8. Testing 2

Install Laravel

//via Laravel Installer
composer global require laravel/installer
laravel new laravel-url-shortener

//via Composer
composer create-project laravel/laravel laravel-url-shortener

In order to develop a URL shortener similar to or in laravel 8, we must first install the most recent version of the framework (currently version 8). You can use the laravel installer or composer, as in the aforementioned example, to install laravel.

Please select one installation technique for Laravel. Both of the aforementioned Laravel installation command examples will result in the creation of a project named Laravel-URL-Shortener.

Install Laravel URL Shortener Package

composer require ashallendesign/short-url

After that, access the project directory and run the aforementioned command via composer to install the short URL package.

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

To publish the configuration file and migration from the package's short URL, issue the same php artisan vendor:publish command as before.

Setup Database


Create a fresh database to house the sample data we'll need for this investigation. Please make a new database at localhost/phpmyadmin if you're using xampp for local development. Here's an illustration: I made a new database called Laravel url shortener. Then, as in the example above, don't forget to update DB DATABASE in the.env file as well. Run the php artisan migrate command after that to migrate all migration files to the database.

Define Route & Logic


use Illuminate\Support\Facades\Route;

| Web Routes
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!

Route::get('/', function () {
    $urls = \AshAllenDesign\ShortURL\Models\ShortURL::latest()->get();
    return view('welcome', compact('urls'));

Route::post('/', function () {
    $builder = new \AshAllenDesign\ShortURL\Classes\Builder();

    $shortURLObject = $builder->destinationUrl(request()->url)->make();
    $shortURL = $shortURLObject->default_short_url;

    return back()->with('success','URL shortened successfully. ');


Route::post('{id}', function ($id) {
    $url = \AshAllenDesign\ShortURL\Models\ShortURL::find($id);
    $url->url_key = request()->url;
    $url->destination_url = request()->destination;

    return back()->with('success','URL updated successfully. ');

In the fourth step, we open the routes/web.php file, update the Laravel default route, and add the two new routes as described before. The welcome.blade.php view file and any URL data that has been successfully inserted or condensed using the Laravel URL shortener are displayed in the first route. Shortened URLs are added to the data via the second route using the POST technique. The third route, which uses the POST method, is used to update or store modified data.

Setup View

<!doctype html>
<html lang="en">
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap CSS -->
        <link href="[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <title>Laravel 8 URL Shortener</title>
        <div class="container my-5">
            <div class="row">
                <h1 class="my-2 fs-4 fw-bold text-center">Laravel URL Shortener</h1>
                <form action="{{ route('url.shorten') }}" method="POST" class="my-2">
                    <div class="input-group mb-3">
                        <input type="text" name="url" class="form-control" placeholder="URL Shortener">
                        <button class="btn btn-outline-secondary" type="submit">Shorten</button>
                @if (session('success'))
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                <table class="table">
                            <th scope="col">#</th>
                            <th scope="col">URL Key</th>
                            <th scope="col">URL Destination</th>
                            <th scope="col">Short URL</th>
                            <th scope="col">Visitors</th>
                            <th scope="col">action</th>
                        @foreach ($urls as $key => $item)
                            <th scope="row">{{ ++$key }}</th>
                            <td>{{ $item->url_key }}</td>
                            <td>{{ $item->destination_url }}</td>
                            <td>{{ $item->default_short_url }}</td>
                            <td>{{ $item->visits->count() }}</td>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal-{{ $key }}">
                        <!-- Modal -->
                        <div class="modal fade" id="exampleModal-{{ $key }}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
                            <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h5 class="modal-title" id="exampleModalLabel">Edit</h5>
                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    <div class="modal-body">
                                        <form action="{{ route('update', $item->id) }}" method="POST">
                                            <div class="mb-3">
                                                <label for="key" class="form-label">URL Key</label>
                                                <input type="text" name="url" value="{{ $item->url_key }}" class="form-control" id="key">
                                            <div class="mb-3">
                                                <label for="destination" class="form-label">Destination URL</label>
                                                <input type="text" name="destination" value="{{ $item->destination_url }}" class="form-control" id="destination">
                                            <button type="submit" class="btn btn-primary">Update</button>
        <script src="[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

Open the welcome.blade.php file for viewing, and then modify the existing code to resemble the code shown above. Using the aforementioned code, we'll add a table using the data from the short urls table using bootstrap 5. We also have forms for adding data and editing URL data in the modal.

Testing 1

The first URL shortener feature is now ready for testing. Please use the php artisan serve command to run your laravel project before launching it in a browser at or laravel-url-shortener.test. Try entering the URL and selecting "shorten" for the first test; the information will then be saved in the short urls table.

Custom Route


'disable_default_route' => true,

Open the config/short-url.php file and change disable default route to true to perform a custom route.


'default_short_url'              => config('app.url').'/short/'.$this->urlKey,

Then, find the aforementioned code in the Builder.php file located in the vendor/ashallendesign/short-url/src/Classes directory, and replace it with the given code.

'default_short_url'              => config('app.url').'/id/'.$this->urlKey,

In this case, we modify the default short url field's value from{URL key} to{URL key}.


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

Then, after opening the routes/web.php file, add a new route using the given code.

$url->default_short_url = config('app.url').'/id/'.request()->url;

Additionally, add the aforementioned code to the update route so that it resembles the code below rather than the current update route.

Route::post('{id}', function ($id) {
    $url = \AshAllenDesign\ShortURL\Models\ShortURL::find($id);
    $url->url_key = request()->url;
    $url->destination_url = request()->destination;
    $url->default_short_url = config('app.url').'/id/'.request()->url;

    return back()->with('success','URL updated successfully. ');

Testing 2

Now let's go on to the second test. Please enter a new URL and click "Shorten" again. The default short url will now appear in the format{URL key}

Recommended Posts

View All

Laravel 9 CKeditor Image Upload With Example

Learn how to easily upload images in CKEditor using Laravel 9 with this step-by-step tutorial and example code. Improve your web development skills no...

Laravel 9 Stripe Payment Gateway Integration Example

Stripe payment gateway for Laravel 9; I'll demonstrate how to include Stripe payment gateway into Laravel 9 apps in this tutorial.

Laravel 9 Scout Full Text Search with Algolia Tutorial

A full-text search feature in a web application is incredibly useful for users to navigate through content-rich web and mobile applications, as demons...

Laravel Routing Tutorial Step by Step

I'll give you a step-by-step instruction on laravel routing in this blog. We'll demonstrate how to make a new route in Laravel and how to make a route...

Building Smarter Web Applications with OpenAI for Laravel

In this tutorial, we'll explore how to use OpenAI in Laravel, and how it can help us build smarter, more efficient web applications.