How to Create URL Shortener using Laravel?

How to Create URL Shortener using Laravel

Hello Laravel Friends,

A Uniform Resource Locator, which we shortly know as URL, is an address that is used to access resources on the database of the internet, like images, websites, or files. The URL provides a specific path to a resource, consisting of several components: the protocol (e.g., HTTP or HTTPS), the domain name (e.g., www.example.com), and the path or specific file location (e.g., /about-us).

URLs are essential for navigating the web, allowing users to find and access information or services on various websites. But long and bulky URLs are inconvenient and aesthetically displeasing in the deep span of the internet. That being the case, concise and user-friendly URLs are always required. Link shortening is a common method to extend URL aesthetics and user experience.

The way to implement link shortening in Laravel is very easy, as Laravel is a powerful PHP web application framework. In this step-by-step guide, we will examine how to create a simple link-shortening feature based on Laravel with practical examples.

In this Laravel tutorial we will learn about creating URL shorter using Laravel.

Steps to Create URL Shortner in Laravel:

Step 1: Setting Up Your Laravel Project

If you haven’t already, install Laravel using Composer:

composer create-project --prefer-dist laravel/laravel link-shortener

Navigate to your project directory:

cd link-shortener

Step 2: Creating the Link Model and Migration

Generate a model and migration for links:

php artisan make:model Link -m

Edit the migration file to define the structure of the ‘links’ table:

Path – database/migrations/YYYY_MM_DD_create_links_table.php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLinksTable extends Migration
{
    public function up()
    {
        Schema::create('links', function (Blueprint $table) {
            $table->id();
            $table->string('original_url');
            $table->string('short_url')->unique();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('links');
    }
}

Run the migration to create the ‘links’ table:

php artisan migrate

Step 3: Implementing Link Shortening Logic

Install the ‘hashids’ package for generating unique, reversible hashes:

composer require vinkla/hashids

Update the Link model to include link shortening logic:

Path – app/Models/Link.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Vinkla\Hashids\Facades\Hashids;

class Link extends Model
{
    use HasFactory;

    protected $fillable = ['original_url', 'short_url'];

    public static function shortenUrl($originalUrl)
    {
        $link = self::create(['original_url' => $originalUrl]);
        $link->short_url = Hashids::encode($link->id);
        $link->save();

        return $link;
    }

    public static function getOriginalUrl($shortUrl)
    {
        $linkId = Hashids::decode($shortUrl);
        $link = self::find($linkId);

        return $link ? $link->original_url : null;
    }
}

Step 4: Creating Routes and Controllers

Generate a controller for link operations:

php artisan make:controller LinkController

Add below code in controller file

Path – app/Http/Controllers/LinkController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Link;

class LinkController extends Controller
{
    public function create()
    {
        return view('create-link');
    }

    public function store(Request $request)
    {
        $request->validate(['url' => 'required|url']);

        $originalUrl = $request->input('url');
        $link = Link::shortenUrl($originalUrl);

        return redirect()->route('link.show', $link->short_url);
    }

    public function show($shortUrl)
    {
        $originalUrl = Link::getOriginalUrl($shortUrl);

        if (!$originalUrl) {
            abort(404);
        }

        return redirect($originalUrl);
    }
}

Define the routes in routes/web.php:

Path – routes/web.php

use App\Http\Controllers\LinkController;

Route::get('/', [LinkController::class, 'create']);
Route::post('/store', [LinkController::class, 'store'])->name('link.store');
Route::get('/{shortUrl}', [LinkController::class, 'show'])->name('link.show');

Step 5: Creating Views

Create a view for link creation:

Path – resources/views/create-link.blade.php

<!-- resources/views/create-link.blade.php -->

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Link Shortener</title>
</head>
<body>
    <h1>Link Shortener</h1>

    <form action="{{ route('link.store') }}" method="post">
        @csrf
        <label for="url">Enter URL:</label>
        <input type="text" name="url" id="url" required>
        <button type="submit">Shorten URL</button>
    </form>
</body>
</html>

Step 6: Deployment and Testing

Deploy your Laravel application and test the link shortening functionality.

Visit http://localhost:8000 in your browser, enter a URL in the form, and submit it. You should be redirected to a shortened URL, and visiting that URL should redirect you to the original link.

Conclusion:

You have successfully built a basic URL shortener using Laravel. Feel free to ask questions through the comment section or contact Laravel developers for any customized requirements.

Share the blog link with your friends and through your social media handles to help others create convenient URLs using link shortening functionality in Laravel.

Happy Coding!

Previous Article

How to Disable the PageBuilder Module for a Specific Field in Magento 2

Next Article

How to Promote Shopify Discount on Facebook?

View Comments (2)
  1. Hi.
    Thank for the article.
    There is one small bug in the code.
    you’ve defined the short_url to be unique.
    in shortenUrl method, at the first line you create a $link with only original_url property.
    it evaluates this error: Field ‘short_url’ doesn’t have a default value.

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨