PHPackages                             shammaa/laravel-url-shortener - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. shammaa/laravel-url-shortener

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

shammaa/laravel-url-shortener
=============================

Professional URL shortener for Laravel with password protection, QR codes, advanced analytics, UTM tracking, and much more

1.1.0(6mo ago)124MITPHPPHP ^8.1

Since Dec 2Pushed 3mo agoCompare

[ Source](https://github.com/shammaa/laravel-url-shortener)[ Packagist](https://packagist.org/packages/shammaa/laravel-url-shortener)[ Docs](https://github.com/shammaa/laravel-url-shortener)[ RSS](/packages/shammaa-laravel-url-shortener/feed)WikiDiscussions main Synced 3w ago

READMEChangelogDependencies (10)Versions (3)Used By (0)

Laravel URL Shortener
=====================

[](#laravel-url-shortener)

A professional, feature-rich URL shortener package for Laravel with password protection, QR codes, advanced analytics, hidden UTM tracking, and much more.

Features
--------

[](#features)

- 🔒 **Password Protection** - Protect your links with passwords
- 📊 **Advanced Analytics** - Track clicks, locations, devices, browsers, and more
- 🎯 **Hidden UTM Tracking** - Track UTM parameters without showing them in URLs
- 📱 **QR Code Generation** - Automatic QR code generation for all links
- ⏰ **Link Expiry** - Set expiration dates for links
- 🔢 **Click Limits** - Limit the number of clicks per link
- 🌍 **Geographic Tracking** - Track visitor locations (country, city)
- 📱 **Device Tracking** - Track devices, browsers, platforms
- 🔗 **Custom Domains** - Use custom domains for shortened URLs
- 🚀 **High Performance** - Optimized with caching
- 🔌 **API Support** - Full REST API included
- 📈 **Real-time Analytics** - Real-time visit tracking
- 🎨 **Professional UI** - Beautiful password protection page
- 🔗 **Model Integration** - Automatic short links for Eloquent models

Installation
------------

[](#installation)

```
composer require shammaa/laravel-url-shortener
```

Publish configuration and migrations:

```
php artisan vendor:publish --tag=url-shortener-config
php artisan vendor:publish --tag=url-shortener-migrations
php artisan migrate
```

Quick Start
-----------

[](#quick-start)

### Basic Usage

[](#basic-usage)

```
use Shammaa\LaravelUrlShortener\Facades\UrlShortener;

// Create a simple short link
$link = UrlShortener::create([
    'destination_url' => 'https://example.com/very-long-url',
]);

echo $link->short_url; // https://yoursite.com/s/abc123
```

### Using Helper Function

[](#using-helper-function)

```
// Simple
$link = short_url('https://example.com');

// With options
$link = short_url('https://example.com', [
    'title' => 'My Link',
    'password' => 'secret123',
    'expires_in_days' => 7,
    'click_limit' => 50,
]);
```

Features in Detail
------------------

[](#features-in-detail)

### Password Protection

[](#password-protection)

```
$link = UrlShortener::create([
    'destination_url' => 'https://example.com/secret',
    'password' => 'my-password',
]);
```

Users will be prompted for a password when accessing the link. The password is verified in session, so they don't need to enter it again.

### QR Code Generation

[](#qr-code-generation)

QR codes are automatically generated for all links:

```
$link = UrlShortener::create([
    'destination_url' => 'https://example.com',
]);

// Access QR code
$qrCodeUrl = $link->qr_code_path; // Storage path

// Or via API
GET /api/url-shortener/links/{key}/qr-code
```

### Hidden UTM Tracking

[](#hidden-utm-tracking)

Track UTM parameters without showing them in the URL:

```
$link = UrlShortener::create([
    'destination_url' => 'https://example.com',
    'utm_parameters' => [
        'utm_source' => 'newsletter',
        'utm_medium' => 'email',
        'utm_campaign' => 'promo2024',
    ],
    'utm_hidden' => true, // Hide in URL but track internally
]);
```

The UTM parameters will be tracked in analytics but won't appear in the destination URL.

### Link Expiry

[](#link-expiry)

```
// Expires in 30 days
$link = UrlShortener::create([
    'destination_url' => 'https://example.com',
    'expires_in_days' => 30,
]);

// Or set specific date
$link = UrlShortener::create([
    'destination_url' => 'https://example.com',
    'expires_at' => now()->addMonths(3),
]);
```

### Click Limits

[](#click-limits)

```
$link = UrlShortener::create([
    'destination_url' => 'https://example.com',
    'click_limit' => 100, // Stops working after 100 clicks
]);
```

### Advanced Analytics

[](#advanced-analytics)

The package automatically tracks:

- Total clicks
- Unique visitors (by IP)
- Geographic location (country, city)
- Device types (desktop, mobile, tablet)
- Browsers and platforms
- Referrers
- UTM parameters
- Time-based statistics

**Access analytics:**

```
$link = UrlShortener::findByKey('abc123');

// Get statistics
$totalClicks = $link->clicks_count;
$uniqueClicks = $link->visits()->distinct('ip_address')->count();
$clicksToday = $link->visits()->today()->count();
$clicksByCountry = $link->visits()->selectRaw('country, COUNT(*) as clicks')
    ->groupBy('country')
    ->get();
```

Using with Models
-----------------

[](#using-with-models)

The `HasShortLink` trait automatically creates short links for any Eloquent model with a **model prefix + random code** format (e.g., `post-xyz1`, `article-abc2`).

### Basic Usage

[](#basic-usage-1)

```
use Shammaa\LaravelUrlShortener\Traits\HasShortLink;

class Post extends Model
{
    use HasShortLink;

    protected $fillable = ['title', 'slug', 'content'];
}

// Create short link
$post = Post::create(['title' => 'My Article']);
$post->createShortLink();

echo $post->short_url; // https://yoursite.com/s/post-xyz1
echo $post->shortLink->key; // post-xyz1
```

### How It Works

[](#how-it-works)

1. **Extracts model name** → `Post` becomes `post`
2. **Generates random code** → `xyz1` (4 characters by default)
3. **Combines them** → `post-xyz1`
4. **Ensures uniqueness** → Checks database and regenerates if needed

### Key Format

[](#key-format)

The trait generates keys in format: `{model-name}-{random-code}`

```
$post->createShortLink();      // Key: "post-xyz1"
$article->createShortLink();   // Key: "article-abc2"
$product->createShortLink();   // Key: "product-def3"
```

### Custom Prefix

[](#custom-prefix)

You can customize the prefix using a database field or method:

**Option 1: Database Field**

```
// Migration
Schema::table('posts', function (Blueprint $table) {
    $table->string('short_link_prefix')->nullable();
});

// Usage
$post->short_link_prefix = 'blog';
$post->createShortLink();
// Key: "blog-xyz1" (instead of "post-xyz1")
```

**Option 2: Override Method**

```
class Post extends Model
{
    use HasShortLink;

    protected function getShortLinkPrefix(): string
    {
        return 'blog'; // Always use "blog" as prefix
    }
}
```

**Priority Order:**

1. Custom field: `short_link_prefix`
2. Custom method: `getShortLinkPrefix()`
3. Model name: Auto-extracted (default)

### Custom Destination URL

[](#custom-destination-url)

```
class Post extends Model
{
    use HasShortLink;

    public function getShortLinkUrl(): string
    {
        return route('posts.show', $this);
    }
}
```

### Automatic Creation

[](#automatic-creation)

Create short links automatically when model is created:

```
class Post extends Model
{
    use HasShortLink;

    protected static function booted()
    {
        static::created(function ($post) {
            $post->createShortLink(['title' => $post->title]);
        });
    }
}
```

### Complete Example

[](#complete-example)

```
// Model
class Post extends Model
{
    use HasShortLink;
    protected $fillable = ['title', 'slug', 'content'];
}

// Routes
Route::get('/posts/{post}', [PostController::class, 'show'])
    ->name('posts.show');

// Controller
public function show(Post $post)
{
    return view('posts.show', ['post' => $post]);
}

// Blade Template
@if($post->hasShortLink())

        Share: {{ $post->short_url }}

@endif
```

### Configuration

[](#configuration)

Customize random code length:

```
// config/url-shortener.php
'model_key_length' => 4, // Default: 4 characters

// Or via .env
URL_SHORTENER_MODEL_KEY_LENGTH=6
```

API Usage
---------

[](#api-usage)

### Endpoints

[](#endpoints)

```
# Create link
POST /api/url-shortener/links
{
    "destination_url": "https://example.com",
    "title": "My Link",
    "password": "secret",
    "expires_in_days": 30,
    "click_limit": 100
}

# Get link
GET /api/url-shortener/links/{key}

# Get analytics
GET /api/url-shortener/links/{key}/analytics

# Get QR code
GET /api/url-shortener/links/{key}/qr-code

# Update link
PUT /api/url-shortener/links/{key}
{
    "is_active": false,
    "expires_at": "2024-12-31 23:59:59"
}

# Delete link
DELETE /api/url-shortener/links/{key}
```

Configuration
-------------

[](#configuration-1)

Edit `config/url-shortener.php`:

```
// Short URL prefix
'prefix' => 's', // Links will be: /s/abc123

// Key length for manually created links
'key_length' => 6,

// Model key length (for HasShortLink trait)
'model_key_length' => 4,

// QR Code settings
'qr_code' => [
    'enabled' => true,
    'size' => 200,
    'format' => 'svg', // svg or png
],

// UTM tracking
'utm' => [
    'enabled' => true,
    'hidden' => true, // Hide in URL but track internally
],

// Tracking options
'track_visits' => true,
'track_ip_address' => true,
'track_user_agent' => true,
'track_referer' => true,
'track_geo' => false, // Requires geolocation service
```

Performance
-----------

[](#performance)

- **Smart Caching** - Links are cached for fast retrieval
- **Optimized Queries** - Efficient database queries with proper indexing
- **Minimal Overhead** - Lightweight tracking with minimal performance impact

License
-------

[](#license)

MIT

Author
------

[](#author)

Shadi Shammaa

Support
-------

[](#support)

For issues and feature requests, please use the GitHub issue tracker.

###  Health Score

35

—

LowBetter than 77% of packages

Maintenance72

Regular maintenance activity

Popularity10

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity45

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~3 days

Total

2

Last Release

203d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/5834300?v=4)[shadishammaa](/maintainers/shadishammaa)[@shadishammaa](https://github.com/shadishammaa)

---

Top Contributors

[![shammaa](https://avatars.githubusercontent.com/u/8601466?v=4)](https://github.com/shammaa "shammaa (6 commits)")

---

Tags

qr codelaravelanalyticsredirectshort urlurl shortenerpassword protectionutm-trackingbitly-alternativelink-tracking

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/shammaa-laravel-url-shortener/health.svg)

```
[![Health](https://phpackages.com/badges/shammaa-laravel-url-shortener/health.svg)](https://phpackages.com/packages/shammaa-laravel-url-shortener)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9742.3M121](/packages/roots-acorn)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

76518.2M120](/packages/laravel-mcp)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)[flarum/core

Delightfully simple forum software.

201.4M2.2k](/packages/flarum-core)[api-platform/laravel

API Platform support for Laravel

59156.3k11](/packages/api-platform-laravel)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
