Sling Academy
Home/PHP/Laravel + Eloquent: Design a Simple URL Shortening Service

Laravel + Eloquent: Design a Simple URL Shortening Service

Last updated: January 28, 2024

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!

Next Article: SMS Notifications in Laravel: A Practical Guide

Previous Article: Observers and Event Listeners in Laravel: A Practical Guide

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array