PHPackages                             legich13/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. legich13/laravel-url-shortener

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

legich13/laravel-url-shortener
==============================

A Laravel package for URL shortening (SOLID‑compliant)

1.0.0(1y ago)11MITPHPPHP &gt;=8.0

Since Apr 17Pushed 1y ago1 watchersCompare

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

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

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

[](#laravel-url-shortener)

[![Latest Version on Packagist](https://camo.githubusercontent.com/724c10bf2207158a7764db231a5d906838199eac0aeca9f633b3054c2ee7d56f/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f76656e646f722f6c61726176656c2d75726c2d73686f7274656e65722e737667)](https://packagist.org/packages/vendor/laravel-url-shortener)[![Total Downloads](https://camo.githubusercontent.com/470d0d43640a3fe5d5c4526cc4dc722a451f6c8ef52a47aa798477941f652455/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f76656e646f722f6c61726176656c2d75726c2d73686f7274656e65722e737667)](https://packagist.org/packages/vendor/laravel-url-shortener)[![Tests](https://github.com/vendor/laravel-url-shortener/actions/workflows/run-tests.yml/badge.svg)](https://github.com/vendor/laravel-url-shortener/actions/workflows/run-tests.yml)

SOLID-принципы в действии: простой и гибкий пакет для сокращения URL в Laravel.

Установка
---------

[](#установка)

Установите пакет через Composer:

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

### Публикация файлов

[](#публикация-файлов)

Опубликуйте конфигурацию и миграции:

```
php artisan vendor:publish --provider="Vendor\UrlShortener\UrlShortenerServiceProvider" --tag="config"
php artisan vendor:publish --provider="Vendor\UrlShortener\UrlShortenerServiceProvider" --tag="migrations"
```

Выполните миграции:

```
php artisan migrate
```

Использование
-------------

[](#использование)

### Сокращение URL с помощью фасада

[](#сокращение-url-с-помощью-фасада)

```
use Vendor\UrlShortener\Facades\UrlShortener;

// Сократить URL
$code = UrlShortener::shorten('https://example.com/long-path');

// Получить полную короткую ссылку
$shortUrl = url(config('url-shortener.route_prefix') . '/' . $code);
```

### Использование в контроллере

[](#использование-в-контроллере)

```
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Vendor\UrlShortener\Services\UrlShortenerService;

class UrlController extends Controller
{
    protected $urlShortener;

    public function __construct(UrlShortenerService $urlShortener)
    {
        $this->urlShortener = $urlShortener;
    }

    public function shorten(Request $request)
    {
        $validated = $request->validate([
            'url' => 'required|url'
        ]);

        $code = $this->urlShortener->shorten($validated['url']);
        $shortUrl = url(config('url-shortener.route_prefix') . '/' . $code);

        return response()->json([
            'original_url' => $validated['url'],
            'short_code' => $code,
            'short_url' => $shortUrl
        ]);
    }

    public function redirect($code)
    {
        $longUrl = $this->urlShortener->expand($code);

        if (!$longUrl) {
            abort(404, 'Короткая ссылка не найдена');
        }

        // Увеличиваем счетчик переходов
        $this->urlShortener->incrementClicks($code);

        // Перенаправляем на оригинальный URL
        return redirect()->away($longUrl);
    }
}
```

### Регистрация собственных маршрутов

[](#регистрация-собственных-маршрутов)

Если вы отключили встроенные маршруты пакета (`'enable_routes' => false`), добавьте собственные в `routes/web.php`:

```
Route::post('urls/shorten', [App\Http\Controllers\UrlController::class, 'shorten'])->name('urls.shorten');
Route::get('u/{code}', [App\Http\Controllers\UrlController::class, 'redirect'])->name('urls.redirect');
```

### Получение длинного URL из кода

[](#получение-длинного-url-из-кода)

```
$longUrl = UrlShortener::expand($code);
```

### Подсчет переходов

[](#подсчет-переходов)

Счетчик переходов увеличивается автоматически при каждом переходе или вручную:

```
UrlShortener::incrementClicks($code);
```

Настройка
---------

[](#настройка)

Вы можете настроить пакет в файле `config/url-shortener.php`:

```
return [
    // Имя таблицы для хранения
    'table' => 'shortened_urls',

    // Включить встроенные маршруты пакета
    'enable_routes' => true,

    // Префикс для всех коротких ссылок (можно пустым)
    'route_prefix' => '',

    // Путь для редиректа (например, '/go/{code}')
    'redirect_path' => '/{code}',
];
```

Тестирование
------------

[](#тестирование)

```
composer test
```

SOLID-принципы
--------------

[](#solid-принципы)

Пакет разработан в соответствии с принципами SOLID:

1. **S** - Single Responsibility Principle: каждый класс имеет одну ответственность
2. **O** - Open/Closed Principle: расширение без модификации через интерфейсы
3. **L** - Liskov Substitution Principle: взаимозаменяемость реализаций через интерфейсы
4. **I** - Interface Segregation Principle: интерфейсы с минимальным набором методов
5. **D** - Dependency Inversion Principle: зависимость от абстракций, а не от конкретных реализаций

License
-------

[](#license)

The MIT License (MIT). См. [License File](LICENSE.md) для дополнительной информации.

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance47

Moderate activity, may be stable

Popularity3

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity42

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

391d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/44b643f4116424350620a31420a7ecc7c04c1131d967b30a1318420f26ab36cb?d=identicon)[Legich13](/maintainers/Legich13)

---

Top Contributors

[![Legich13](https://avatars.githubusercontent.com/u/60274918?v=4)](https://github.com/Legich13 "Legich13 (3 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[barryvdh/laravel-ide-helper

Laravel IDE Helper, generates correct PHPDocs for all Facade classes, to improve auto-completion.

14.9k123.0M687](/packages/barryvdh-laravel-ide-helper)[orchestra/canvas

Code Generators for Laravel Applications and Packages

21017.2M158](/packages/orchestra-canvas)[illuminate/pipeline

The Illuminate Pipeline package.

9446.6M213](/packages/illuminate-pipeline)[illuminate/pagination

The Illuminate Pagination package.

10532.5M862](/packages/illuminate-pagination)[spatie/laravel-pjax

A pjax middleware for Laravel 5

513371.8k11](/packages/spatie-laravel-pjax)[spatie/laravel-mix-preload

Add preload and prefetch links based your Mix manifest

169176.0k2](/packages/spatie-laravel-mix-preload)

PHPackages © 2026

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