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