Laravel + Eloquent: Design a Simple URL Shortening Service

Updated: January 28, 2024 By: Guest Contributor Post a comment

Getting Started

URL shortening services have become an essential tool in the age of social media and online marketing. They simplify long URLs, making them easier to share and manage. In this tutorial, we’ll learn how to build a basic URL shortening service using Laravel and Eloquent ORM. This will include setting up the database, creating models, and defining routes.

Create a new Laravel project:

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

Now, create a database and configure your .env file to connect to it.

Database & Migrations

We’ll start by creating a migration for our shortened_urls table:

php artisan make:migration create_shortened_urls_table --create=shortened_urls

Edit the migration file located in database/migrations folder and add fields:

Schema::create('shortened_urls', function (Blueprint $table) {
    $table->id();
    $table->string('code')->unique();
    $table->string('url');
    $table->timestamps();
});

Now, migrate your database:

php artisan migrate

Creating the Model

Create an Eloquent Model:

php artisan make:model ShortenedUrl

Edit the ShortenedUrl model:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class ShortenedUrl extends Model
{
    protected $fillable = ['url', 'code'];
}

Handling URL Shortening Logic

We need a mechanism to generate a unique code for each URL. For this example, let’s handle it simply:

public static function boot()
{
    parent::boot();
    self::creating(function ($model) {
        $model->code = substr(md5(uniqid(rand(), true)), 0, 6);
    });
}

Add this to your ShortenedUrl model.

Routing and Controllers

Create a controller to handle the web requests:

php artisan make:controller UrlShortenerController

Edit the UrlShortenerController:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\ShortenedUrl;

class UrlShortenerController extends Controller
{
    public function store(Request $request)
    {
        $request->validate(['url' => 'required|url']);
        $shortenedUrl = ShortenedUrl::create(['url' => $request->url]);
        return response()->json(['code' => $shortenedUrl->code], 201);
    }

    public function show($code)
    {
        $url = ShortenedUrl::where('code', $code)->firstOrFail();
        return redirect($url->url);
    }
}

Define the routes:

use App\Http\Controllers\UrlShortenerController;

Route::post('/shorten', [UrlShortenerController::class, 'store']);
Route::get('/{code}', [UrlShortenerController::class, 'show']);

Testing Our Service

Use curl or a http client like Postman to test your service:

curl -X POST -F 'url=https://www.google.com' http://localhost/shorten

You will receive a JSON response with your unique code that redirects to the original URL.

Conclusion

In this guide, we’ve gone through the steps to create a simple URL shortening service with Laravel and Eloquent. Your new service encompasses core components such as migrations, models, routing, and controllers. While simple, this provides a baseline upon which more complex features can be built, like analytics, custom aliasing or user authentication.

Happy coding!