laravel
  1. laravel-create-url-shortener-in-laravel

Create URL Shortener in Laravel - ( Laravel Misc. )

URL shortening is a technique that allows you to shorten a long URL into a shorter one. In this article, we'll build a URL shortener using Laravel, a popular PHP web application framework.

Overview

Our URL shortener will be a simple web application that will allow users to enter a long URL and generate a short URL for it. The short URL will then redirect the user to the original long URL when clicked.

Setting Up the Laravel Project

To get started, create a new Laravel project using the following command:

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

Next, navigate to the project directory and start the development server:

$ cd shortener
$ php artisan serve

Creating the Database

Our URL shortener will need a database to store the details of the long and short URLs. To create a new database, run the following command in the terminal:

$ php artisan make:migration create_urls_table --create=urls

This will create a new migration file in the database/migrations directory. Open the migration file and add the following code:

<?php

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

class CreateUrlsTable extends Migration
{
    public function up()
    {
        Schema::create('urls', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('long_url');
            $table->text('short_url')->unique();
            $table->timestamps();
        });
    }

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

This migration will create a new table named urls with three columns: id, long_url, and short_url, and timestamps.

Run the migration to create the table in the database:

$ php artisan migrate

Creating the URL Shortener

Now that we have our database set up, we can create the URL shortening functionality. We'll create a new controller named UrlController that will handle the URL shortening and redirection.

Run the following command in the terminal to create the controller:

$ php artisan make:controller UrlController

Open the UrlController and add the following code to the index method:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UrlController extends Controller
{
    public function index()
    {
        return view('shorten');
    }
}

This method will return a view named shorten.blade.php, which will contain a form to submit the long URL.

Create a new file named shorten.blade.php in the resources/views directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>URL Shortener</title>
</head>
<body>
    <h1>URL Shortener</h1>

    <form method="post" action="{{ route('urls.store') }}">
        @csrf
        <input type="text" name="long_url" placeholder="Enter a long URL">
        <button type="submit">Shorten</button>
    </form>
</body>
</html>

This view contains a form with a single text input to enter the long URL and a submit button to send the form data to the server.

Next, add the following code to the store method in the UrlController:

public function store(Request $request)
{
    $longUrl = $request->input('long_url');

    $shortUrl = str_random(6);

    DB::table('urls')->insert([
        'long_url' => $longUrl,
        'short_url' => $shortUrl,
        'created_at' => now(),
        'updated_at' => now()
    ]);

    return redirect('/')->with('success', 'Short URL generated successfully!');
}

This method first gets the long URL and generates a random 6-character string for the short URL. It then inserts the long and short URLs into the database table named urls along with the current date and time. Finally, it redirects the user back to the shorten.blade.php view with a success message.

The last step is to create a new method named redirectUrl in the UrlController that will handle the redirection from the short URL to the long URL:

public function redirectUrl($shortUrl)
{
    $url = DB::table('urls')->where('short_url', $shortUrl)->first();

    if ($url) {
        DB::table('urls')->where('id', $url->id)->increment('clicks');

        return redirect($url->long_url);
    }

    abort(404);
}

This method first queries the urls table in the database to find the long URL associated with the given short URL. If a match is found, it increments the clicks column for that URL and redirects the user to the long URL. If no match is found, it returns a 404 error.

Finally, create a new route in the routes/web.php file to handle the URL redirection:

Route::get('/{shortUrl}', 'UrlController@redirectUrl');

Testing the URL Shortener

To test our URL shortener, start the Laravel server:

$ php artisan serve

Then, navigate to http://localhost:8000 in your web browser. You should see the shorten.blade.php view with a form to enter a long URL. After submitting the form, you should be redirected back to the shorten.blade.php view with a success message and a short URL. Click on the short URL to see it redirect you to the original long URL.

Summary

In this article, we built a simple URL shortener using Laravel, a popular PHP web application framework. We used a database to store the long and short URLs, and created a controller to handle the URL shortening and redirection. This URL shortener is a great way to make long URLs more manageable and shareable.

Published on: