
Create url shortener in Laravel
Creating a URL shortener in Laravel involves generating shortened versions of long URLs and redirecting users from the short URLs to the original long URLs. Here’s a step-by-step guide to creating a simple URL shortener using Laravel:
- Create a New Laravel Project: If you don’t already have a Laravel project, create one using Composer:
composer create-project laravel/laravel UrlShortener
- Set Up Database: Configure your database connection in the
.env
file and run migrations to set up the necessary tables:
php artisan migrate
- Create Model and Migration: Create a model and migration for the
Link
table:
php artisan make:model Link -m
In the generated migration file (database/migrations/yyyy_mm_dd_create_links_table.php
), define the columns for the links
table, such as original_url
and short_code
.
- Run Migrations: Run migrations to create the
links
table:
php artisan migrate
- Create Controller: Generate a controller for handling URL shortening and redirection:
php artisan make:controller UrlShortenerController
In the UrlShortenerController.php
file, add methods for shortening URLs and redirecting to the original URLs.
- Implement URL Shortening Logic: In the
UrlShortenerController
‘sshorten
method, generate a unique short code and store the original URL and short code in thelinks
table:
public function shorten(Request $request)
{
$originalUrl = $request->input('url');
$shortCode = Str::random(6); // Generate a unique short code
Link::create([
'original_url' => $originalUrl,
'short_code' => $shortCode,
]);
return route('short', $shortCode);
}
- Implement Redirection Logic: In the
UrlShortenerController
‘sredirect
method, retrieve the original URL associated with the short code and redirect the user:
public function redirect($shortCode)
{
$link = Link::where('short_code', $shortCode)->firstOrFail();
return redirect($link->original_url);
}
- Define Routes: Define routes for the URL shortener in
routes/web.php
:
use App\Http\Controllers\UrlShortenerController;
Route::get('/', function () {
return view('welcome');
});
Route::post('/shorten', [UrlShortenerController::class, 'shorten'])->name('shorten');
Route::get('/{shortCode}', [UrlShortenerController::class, 'redirect'])->name('short');
- Create Views: Create views to display the URL shortener form and success page. You can use Blade templates for this purpose.
- Start the Development Server: Start the Laravel development server:
php artisan serve
Now, when you access your application’s URL, you’ll see the URL shortener form. After submitting a long URL, you’ll be redirected to a shortened URL, and accessing the shortened URL will redirect you to the original URL.
Remember that this is a basic example of a URL shortener. For a production system, you might want to consider adding more features, validation, user accounts, and enhanced security measures.