PHPackages                             mepsd/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. [API Development](/categories/api)
4. /
5. mepsd/laravel-url-shortener

ActiveLibrary[API Development](/categories/api)

mepsd/laravel-url-shortener
===========================

Laravel package to interact with the URL Shortener API service

v1(5mo ago)0294↓33.3%MITPHPPHP ^8.1

Since Dec 14Pushed 5mo agoCompare

[ Source](https://github.com/mepsd/laravel-url-shortener)[ Packagist](https://packagist.org/packages/mepsd/laravel-url-shortener)[ Docs](https://github.com/mepsd/laravel-url-shortener)[ RSS](/packages/mepsd-laravel-url-shortener/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (1)Dependencies (5)Versions (2)Used By (0)

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

[](#laravel-url-shortener)

A Laravel package to interact with the URL Shortener API service. Easily create, manage, and track short URLs in your Laravel application.

[![Latest Version on Packagist](https://camo.githubusercontent.com/77eb9be0eab9a40405785380313ef308e0f84a7b89feb6d2b6e541928c55a811/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d657073642f6c61726176656c2d75726c2d73686f7274656e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mepsd/laravel-url-shortener)[![Total Downloads](https://camo.githubusercontent.com/bc2ed97698d3c3ad2465f6ae6514de3fc35f344c256421c93e889646be96580d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d657073642f6c61726176656c2d75726c2d73686f7274656e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mepsd/laravel-url-shortener)[![License](https://camo.githubusercontent.com/dc17cf62c358d444c01fd315b06f0663763bbb69a2ae1180bb0162f76116cc6d/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d657073642f6c61726176656c2d75726c2d73686f7274656e65722e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/mepsd/laravel-url-shortener)

Features
--------

[](#features)

- Create short URLs with optional custom keys
- List, retrieve, update, and delete short URLs
- Get detailed analytics and statistics
- Built-in retry mechanism for failed requests
- Comprehensive error handling
- Facade and dependency injection support
- Fully typed with PHP 8.1+ features

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- Laravel 10.x, 11.x, or 12.x
- Guzzle HTTP Client

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

[](#installation)

Install the package via Composer:

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

The package will auto-register its service provider and facade.

### Publish Configuration

[](#publish-configuration)

Publish the configuration file:

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

This will create a `config/url-shortener.php` file.

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

[](#configuration)

Add the following environment variables to your `.env` file:

```
URL_SHORTENER_BASE_URL=https://your-shortener-domain.com
URL_SHORTENER_API_TOKEN=your-api-token-here
```

### Full Configuration Options

[](#full-configuration-options)

```
// config/url-shortener.php

return [
    // Base URL of your URL shortener service
    'base_url' => env('URL_SHORTENER_BASE_URL', 'http://localhost:8000'),

    // API token for authentication
    'api_token' => env('URL_SHORTENER_API_TOKEN'),

    // API version (default: v1)
    'api_version' => env('URL_SHORTENER_API_VERSION', 'v1'),

    // Request timeout in seconds
    'timeout' => env('URL_SHORTENER_TIMEOUT', 30),

    // Retry configuration
    'retries' => [
        'times' => env('URL_SHORTENER_RETRY_TIMES', 3),
        'sleep' => env('URL_SHORTENER_RETRY_SLEEP', 100), // milliseconds
    ],

    // Default options for creating short URLs
    'defaults' => [
        'track_visits' => true,
        'is_single_use' => false,
    ],
];
```

Usage
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Create a short URL
$shortUrl = UrlShortener::create('https://example.com/very-long-url');

echo $shortUrl->shortUrl;     // https://short.url/abc123
echo $shortUrl->key;          // abc123
echo $shortUrl->destinationUrl; // https://example.com/very-long-url
```

### Using Dependency Injection

[](#using-dependency-injection)

```
use Mepsd\UrlShortener\UrlShortener;

class MyController
{
    public function __construct(
        protected UrlShortener $urlShortener
    ) {}

    public function shorten(Request $request)
    {
        $shortUrl = $this->urlShortener->create($request->url);

        return response()->json($shortUrl);
    }
}
```

### Create Short URLs

[](#create-short-urls)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Basic usage
$shortUrl = UrlShortener::create('https://example.com/my-long-url');

// With custom options
$shortUrl = UrlShortener::create('https://example.com/my-long-url', [
    'custom_key' => 'my-custom-key',  // Custom short URL key
    'title' => 'My Link',              // Optional title
    'track_visits' => true,            // Track visit analytics
    'is_single_use' => false,          // Delete after first use
]);

// Using the alias method
$shortUrl = UrlShortener::shorten('https://example.com/my-long-url');
```

### List URLs

[](#list-urls)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Get paginated list of URLs
$result = UrlShortener::list();

foreach ($result->items as $url) {
    echo $url->shortUrl . ' -> ' . $url->destinationUrl;
}

// With pagination
$result = UrlShortener::list(
    page: 2,
    perPage: 25,
    mineOnly: true  // Only URLs created by current API token
);

// Check pagination info
echo "Page {$result->currentPage} of {$result->lastPage}";
echo "Total URLs: {$result->total}";

if ($result->hasMorePages()) {
    // Fetch next page
}
```

### Get URL Details

[](#get-url-details)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

$shortUrl = UrlShortener::get('abc123');

echo $shortUrl->id;
echo $shortUrl->key;
echo $shortUrl->shortUrl;
echo $shortUrl->destinationUrl;
echo $shortUrl->title;
echo $shortUrl->trackVisits;
echo $shortUrl->isActive;
echo $shortUrl->totalClicks;
echo $shortUrl->uniqueVisitors;
echo $shortUrl->createdAt->format('Y-m-d');

// Using alias
$shortUrl = UrlShortener::find('abc123');
```

### Get URL Statistics

[](#get-url-statistics)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Get stats for last 30 days (default)
$stats = UrlShortener::stats('abc123');

// Get stats for custom period
$stats = UrlShortener::stats('abc123', days: 7);

echo $stats->totalClicks;
echo $stats->uniqueVisitors;
echo $stats->clicksToday;

// Detailed breakdowns
foreach ($stats->browsers as $browser => $count) {
    echo "{$browser}: {$count} visits";
}

foreach ($stats->devices as $device => $count) {
    echo "{$device}: {$count} visits";
}

foreach ($stats->operatingSystems as $os => $count) {
    echo "{$os}: {$count} visits";
}

// Clicks over time
foreach ($stats->clicksOverTime as $day) {
    echo "{$day['date']}: {$day['clicks']} clicks";
}
```

### Update URLs

[](#update-urls)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Update specific fields
$shortUrl = UrlShortener::update('abc123', [
    'title' => 'New Title',
    'is_active' => true,
    'track_visits' => false,
]);

// Activate/Deactivate shortcuts
$shortUrl = UrlShortener::activate('abc123');
$shortUrl = UrlShortener::deactivate('abc123');
```

### Delete URLs

[](#delete-urls)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

$deleted = UrlShortener::delete('abc123'); // Returns true on success
```

### Health Check

[](#health-check)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Get health status
$health = UrlShortener::health();
// Returns: ['status' => 'ok', 'tenant' => 'tenant-id', 'timestamp' => '...']

// Quick check
if (UrlShortener::isHealthy()) {
    // API is accessible
}
```

### Dynamic Configuration

[](#dynamic-configuration)

```
use Mepsd\UrlShortener\Facades\UrlShortener;

// Change token at runtime
UrlShortener::setToken('new-api-token')
    ->create('https://example.com');

// Change base URL at runtime
UrlShortener::setBaseUrl('https://different-shortener.com')
    ->create('https://example.com');

// Chain configuration
$shortUrl = UrlShortener::setBaseUrl('https://shortener.com')
    ->setToken('token')
    ->create('https://example.com');
```

### Creating a New Instance

[](#creating-a-new-instance)

```
use Mepsd\UrlShortener\UrlShortener;

// Create a completely new instance with custom config
$shortener = new UrlShortener(
    baseUrl: 'https://custom-shortener.com',
    apiToken: 'custom-token',
    apiVersion: 'v1',
    timeout: 60,
    retryConfig: ['times' => 5, 'sleep' => 200]
);

$shortUrl = $shortener->create('https://example.com');
```

Error Handling
--------------

[](#error-handling)

The package throws `UrlShortenerException` for all errors:

```
use Mepsd\UrlShortener\Facades\UrlShortener;
use Mepsd\UrlShortener\Exceptions\UrlShortenerException;

try {
    $shortUrl = UrlShortener::create('https://example.com');
} catch (UrlShortenerException $e) {
    // Handle specific error codes
    switch ($e->getCode()) {
        case 401:
            // Unauthorized - invalid API token
            break;
        case 402:
            // Insufficient credits in wallet
            break;
        case 404:
            // URL not found
            break;
        case 422:
            // Validation error
            $errors = $e->getErrors();
            break;
        default:
            // Other error
            $message = $e->getMessage();
            $response = $e->getResponse();
    }
}
```

Data Transfer Objects
---------------------

[](#data-transfer-objects)

The package returns typed DTOs for all responses:

### ShortUrl

[](#shorturl)

```
class ShortUrl {
    public readonly int $id;
    public readonly string $key;
    public readonly string $shortUrl;
    public readonly string $destinationUrl;
    public readonly ?string $title;
    public readonly bool $trackVisits;
    public readonly bool $isActive;
    public readonly ?int $totalClicks;
    public readonly ?int $uniqueVisitors;
    public readonly ?DateTimeImmutable $createdAt;
    public readonly ?DateTimeImmutable $updatedAt;
}
```

### UrlStats

[](#urlstats)

```
class UrlStats {
    public readonly string $key;
    public readonly int $totalClicks;
    public readonly int $uniqueVisitors;
    public readonly int $clicksToday;
    public readonly array $clicksOverTime;
    public readonly array $browsers;
    public readonly array $devices;
    public readonly array $operatingSystems;
    public readonly array $referers;
}
```

### PaginatedResult

[](#paginatedresult)

```
class PaginatedResult implements Countable, IteratorAggregate {
    public readonly array $items;
    public readonly int $currentPage;
    public readonly int $lastPage;
    public readonly int $perPage;
    public readonly int $total;

    public function hasMorePages(): bool;
    public function isEmpty(): bool;
    public function isNotEmpty(): bool;
}
```

API Reference
-------------

[](#api-reference)

MethodDescription`create(string $url, array $options = [])`Create a new short URL`shorten(string $url, array $options = [])`Alias for create()`list(int $page = 1, int $perPage = 15, bool $mineOnly = false)`List URLs with pagination`get(string $key)`Get URL details`find(string $key)`Alias for get()`stats(string $key, int $days = 30)`Get URL statistics`update(string $key, array $data)`Update a URL`activate(string $key)`Activate a URL`deactivate(string $key)`Deactivate a URL`delete(string $key)`Delete a URL`health()`Get API health status`isHealthy()`Check if API is healthy`setToken(string $token)`Set API token dynamically`setBaseUrl(string $baseUrl)`Set base URL dynamicallyTesting
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security-related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [MEPSD](https://github.com/mepsd)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

36

—

LowBetter than 82% of packages

Maintenance72

Regular maintenance activity

Popularity15

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

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

Unknown

Total

1

Last Release

156d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/2d208c2df0bb5813d6d4d2286ef5e000d3666020e5e3548879616781b1113588?d=identicon)[mepsd](/maintainers/mepsd)

---

Top Contributors

[![mepsd](https://avatars.githubusercontent.com/u/45997529?v=4)](https://github.com/mepsd "mepsd (1 commits)")

---

Tags

laravelapi clientshort urlurl shortenermepsd

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[irazasyed/telegram-bot-sdk

The Unofficial Telegram Bot API PHP SDK

3.3k4.5M84](/packages/irazasyed-telegram-bot-sdk)[essa/api-tool-kit

set of tools to build an api with laravel

52680.5k](/packages/essa-api-tool-kit)[flat3/lodata

OData v4.01 Producer for Laravel

96320.9k](/packages/flat3-lodata)[simplestats-io/laravel-client

Client for SimpleStats!

4515.5k](/packages/simplestats-io-laravel-client)[dragon-code/laravel-json-response

Automatically always return a response in JSON format

1118.6k1](/packages/dragon-code-laravel-json-response)[surface/laravel-webfinger

A Laravel package to create an ActivityPub webfinger.

113.8k](/packages/surface-laravel-webfinger)

PHPackages © 2026

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