---
title: "How to Create URL Shortener using Laravel?"
url: "https://magecomp.com/blog/create-url-shortener-laravel/"
date: "2023-12-20T11:58:48+00:00"
modified: "2025-01-28T11:32:01+00:00"
author:
  name: "Bharat Desai"
  url: "https://magecomp.com"
categories:
  - "Laravel"
word_count: 806
reading_time: "5 min read"
summary: "Hello Laravel Friends,"
description: "In this tutorial, you will learn how to build a URL shortener using the Laravel PHP framework."
keywords: "Laravel"
language: "en"
schema_type: "Article"
related_posts:
  - title: "Laravel 13 Action Classes Example"
    url: "https://magecomp.com/blog/laravel-13-action-classes/"
  - title: "How to Create Custom Error Page in Laravel 11?"
    url: "https://magecomp.com/blog/create-custom-error-page-laravel-11/"
  - title: "How to Implement Queue in Laravel 8?"
    url: "https://magecomp.com/blog/implement-queue-laravel-8/"
---

# How to Create URL Shortener using Laravel?

_Published: December 20, 2023_  
_Author: Bharat Desai_  

![How to Create URL Shortener using Laravel](https://magecomp.com/blog/wp-content/uploads/2023/12/How-to-Create-URL-Shortener-using-Laravel-1024x512.webp)

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

[![Laravel Development Services](https://magecomp.com/blog/wp-content/uploads/2024/12/Laravel-Development-Services-4.webp)](https://magecomp.com/services/laravel-development-services/)

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 IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;

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 AppModels;

use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
use VinklaHashidsFacadesHashids;

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;
    }
}
```

### [![Hire laravel Developer](https://magecomp.com/blog/wp-content/uploads/2024/12/Hire-Laravel-Expert-Now-3.webp)](https://magecomp.com/services/hire-laravel-developer/)

### 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 AppHttpControllers;

use IlluminateHttpRequest;
use AppModelsLink;

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 AppHttpControllersLinkController;

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

<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**](https://magecomp.com/hire-laravel-developer.html) for any customized requirements.
[![Contact Us](https://magecomp.com/blog/wp-content/uploads/2024/12/Contact-Us-3.webp)](https://magecomp.com/contact)

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!**

</body></html>


---

_View the original post at: [https://magecomp.com/blog/create-url-shortener-laravel/](https://magecomp.com/blog/create-url-shortener-laravel/)_  
_Served as markdown by [Third Audience](https://github.com/third-audience) v3.5.3_  
_Generated: 2026-08-09 21:00:17 UTC_  
