Hello Laravel Friends,
This Laravel tutorial illustrates How to Create URL Shortener using Laravel.
In the vast landscape of the internet, long and cumbersome URLs can be inconvenient and aesthetically unpleasing. Hence, the need for concise and user-friendly URLs is ever-growing. Link shortening is a popular technique that not only makes URLs more aesthetically pleasing but also enhances user experience.
Laravel, a powerful PHP web application framework, provides an ideal environment for implementing link shortening seamlessly. In this step-by-step guide, we’ll look into how to set up a basic link shortening functionality using Laravel, complete with practical examples.
Contents
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
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
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; } }
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');
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>
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.
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!
Hello Magento Friends, In today’s blog, I will explain How to Add Tooltip in Checkout…
MongoDB is a popular NoSQL database that offers flexibility and scalability when handling modern web…
In NodeJS, callbacks empower developers to execute asynchronous operations like reading files, handling requests, and…
Hello Magento Friends, In today’s blog, we will learn How to Show SKU in Order…
The "Buy Now" and "Add to Cart" buttons serve as the primary call-to-action (CTA) elements…
Hello Magento Friends, In Magento 2, the checkout process allows customers to choose multiple shipping…
View Comments
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.
You can simplify by using $table->string('short_url')->nullable()->unique(); to make the short_url field nullable and unique.