You are probably already familiar with URL shortening services like bit.ly or s.id. 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 s.id or bit.ly 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

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_url_shortener
DB_USERNAME=root
DB_PASSWORD=

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

<?php

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. ');

})->name('url.shorten');

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

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

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">
    <head>
        <!-- Required meta tags -->
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <!-- Bootstrap CSS -->
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
        <title>Laravel 8 URL Shortener</title>
    </head>
    <body>
        <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">
                    @csrf
                    <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>
                    </div>
                </form>
                @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>
                </div>
                @endif
                <table class="table">
                    <thead>
                        <tr>
                            <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>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($urls as $key => $item)
                        <tr>
                            <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>
                            <td>
                                <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal-{{ $key }}">
                                Edit
                                </button>
                            </td>
                        </tr>
                        <!-- 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>
                                    <div class="modal-body">
                                        <form action="{{ route('update', $item->id) }}" method="POST">
                                            @csrf
                                            <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>
                                            <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">
                                            </div>
                                            <button type="submit" class="btn btn-primary">Update</button>
                                        </form>
                                    </div>
                                </div>
                            </div>
                        </div>
                        @endforeach  
                    </tbody>
                </table>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
    </body>
</html>

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 127.0.0.1:8000 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

Confg/short-url.php

'disable_default_route' => true,

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

vendor/ashallendesign/short-url/src/Classes/Builder.php

'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 domain.com/short/{URL key} to domain.com/id/{URL key}.

routes/web.php

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;
    $url->save();

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

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 domain.com/id/{URL key}


Recommended Posts

View All

Create Zip file and Download in Laravel 9


After we have compressed the files, let's download the Laravel 9 zip files. In this tutorial, we'll use the ZipArchive class and a Laravel package to...

Laravel 9 Captcha Tutorial – Create Captcha in Laravel


A CAPTCHA is a challenge-response test used in computing to determine if a user is human. It is an abbreviation for the Completely Automated Public Tu...

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...

Laravel 8/7/6 Google ReCaptcha v2 Form Validation


In form validation, Laravel 8,7,6 uses Google v2 Captcha/Re-Captcha. You will learn how to add Google v2 ReCaptcha form validation to a Laravel form i...

Laravel 8 Import Export Excel & CSV File Example


Using the Maatwebsite/Laravel-Excel package, you will learn how to easily import and export Excel and CSV files in the Laravel 8 application while com...