PHPackages                             philiprehberger/laravel-slug-generator - 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. [Database &amp; ORM](/categories/database)
4. /
5. philiprehberger/laravel-slug-generator

ActiveLibrary[Database &amp; ORM](/categories/database)

philiprehberger/laravel-slug-generator
======================================

Automatic slug generation for Eloquent models with scoped uniqueness, history, and transliteration

v1.1.0(4mo ago)172MITPHPPHP ^8.2CI passing

Since Mar 9Pushed 1mo agoCompare

[ Source](https://github.com/philiprehberger/laravel-slug-generator)[ Packagist](https://packagist.org/packages/philiprehberger/laravel-slug-generator)[ Docs](https://github.com/philiprehberger/laravel-slug-generator)[ RSS](/packages/philiprehberger-laravel-slug-generator/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (19)Versions (7)Used By (0)

Laravel Slug Generator
======================

[](#laravel-slug-generator)

[![Tests](https://github.com/philiprehberger/laravel-slug-generator/actions/workflows/tests.yml/badge.svg)](https://github.com/philiprehberger/laravel-slug-generator/actions/workflows/tests.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/26d700814bb147a909a65b1330ec9a1e56b059a86f4b339439d6769dbfc76c0c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7068696c69707265686265726765722f6c61726176656c2d736c75672d67656e657261746f722e737667)](https://packagist.org/packages/philiprehberger/laravel-slug-generator)[![Last updated](https://camo.githubusercontent.com/6fb2f490a08654c579ebed12639e632203ca1e2f1809470d2c332cfae84c0b07/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6173742d636f6d6d69742f7068696c69707265686265726765722f6c61726176656c2d736c75672d67656e657261746f72)](https://github.com/philiprehberger/laravel-slug-generator/commits/main)

Automatic slug generation for Eloquent models with scoped uniqueness, history, and transliteration.

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

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12

The PHP `intl` extension is recommended for best transliteration results (falls back to `iconv` then a simple strip).

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

[](#installation)

```
composer require philiprehberger/laravel-slug-generator
```

The service provider is auto-discovered via Laravel's package discovery. No manual registration is required.

### Publish configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=slug-generator-config
```

This creates `config/slug-generator.php` in your application.

### Publish and run the slug history migration (optional)

[](#publish-and-run-the-slug-history-migration-optional)

Only required if you intend to use the `HasSlugHistory` trait.

```
php artisan vendor:publish --tag=slug-generator-migrations
php artisan migrate
```

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Add the `HasSlug` trait to any Eloquent model:

```
use Illuminate\Database\Eloquent\Model;
use PhilipRehberger\SlugGenerator\Concerns\HasSlug;

class Post extends Model
{
    use HasSlug;
}
```

The trait reads from the `title` column by default and writes to `slug`:

```
$post = Post::create(['title' => 'Hello World']);
echo $post->slug; // 'hello-world'
```

Duplicate slugs automatically receive a numeric suffix:

```
Post::create(['title' => 'Hello World']); // slug: 'hello-world'
Post::create(['title' => 'Hello World']); // slug: 'hello-world-2'
```

### Per-Model Overrides

[](#per-model-overrides)

```
class Article extends Model
{
    use HasSlug;

    public function slugSource(): string|array  { return 'title'; }
    public function slugField(): string          { return 'slug'; }
    public function slugSeparator(): string      { return '-'; }
    public function slugMaxLength(): ?int        { return null; }
    public function slugShouldBeUnique(): bool   { return true; }
    public function slugUniqueScope(): ?string   { return null; }
    public function slugOnUpdate(): bool         { return false; }
}
```

### Scoped Uniqueness

[](#scoped-uniqueness)

```
class Post extends Model
{
    use HasSlug;

    public function slugUniqueScope(): ?string
    {
        return 'category_id';
    }
}
```

### Slug Template

[](#slug-template)

Use a template pattern to control how attributes are combined in the slug:

```
class Author extends Model
{
    use HasSlug;

    public function slugTemplate(): ?string
    {
        return '{last_name}-{first_name}';
    }
}

$author = Author::create(['first_name' => 'John', 'last_name' => 'Doe']);
echo $author->slug; // 'doe-john'
```

Placeholders use the `{attribute}` syntax and are resolved from model attributes before slugification. Missing or null attributes are omitted from the result.

### Slug History and Redirects

[](#slug-history-and-redirects)

```
use PhilipRehberger\SlugGenerator\Concerns\HasSlug;
use PhilipRehberger\SlugGenerator\Concerns\HasSlugHistory;

class Post extends Model
{
    use HasSlug;
    use HasSlugHistory;

    public function slugOnUpdate(): bool { return true; }
}
```

Use `findBySlugOrRedirect()` in controllers to handle current and old slugs transparently:

```
public function show(string $slug): Response
{
    $result = Post::findBySlugOrRedirect($slug);

    if ($result === null) { abort(404); }

    if (is_array($result) && $result['redirect']) {
        return redirect(route('posts.show', $result['slug']), 301);
    }

    return view('posts.show', ['post' => $result]);
}
```

API
---

[](#api)

### HasSlug Trait — Override Methods

[](#hasslug-trait--override-methods)

MethodReturn TypeDefaultDescription`slugSource()``string|array``'title'`Source column(s) to generate slug from`slugField()``string``'slug'`Database column to store the slug`slugSeparator()``string``'-'`Word separator`slugMaxLength()``?int``null`Max length; truncates at word boundary`slugShouldBeUnique()``bool``true`Enforce unique slugs`slugUniqueScope()``?string``null`Column to scope uniqueness checks`slugTemplate()``?string``null`Template pattern with `{attribute}` placeholders`slugOnUpdate()``bool``false`Regenerate slug on model update### HasSlugHistory Trait

[](#hasslughistory-trait)

MethodDescription`Post::findBySlugOrRedirect(string $slug)`Returns model, redirect array, or null`->slugHistories`MorphMany relationship to slug history records### SlugRedirectMiddleware Parameters

[](#slugredirectmiddleware-parameters)

PositionNameDescription1`modelClass`Fully-qualified model class (must use `HasSlugHistory`)2`routeParam`Route parameter name that holds the slug (default: `slug`)3`urlPrefix`URL prefix for the redirect target (default: `/`)Development
-----------

[](#development)

```
composer install
vendor/bin/phpunit
vendor/bin/pint --test
vendor/bin/phpstan analyse
```

Support
-------

[](#support)

If you find this project useful:

⭐ [Star the repo](https://github.com/philiprehberger/laravel-slug-generator)

🐛 [Report issues](https://github.com/philiprehberger/laravel-slug-generator/issues?q=is%3Aissue+is%3Aopen+label%3Abug)

💡 [Suggest features](https://github.com/philiprehberger/laravel-slug-generator/issues?q=is%3Aissue+is%3Aopen+label%3Aenhancement)

❤️ [Sponsor development](https://github.com/sponsors/philiprehberger)

🌐 [All Open Source Projects](https://philiprehberger.com/open-source-packages)

💻 [GitHub Profile](https://github.com/philiprehberger)

🔗 [LinkedIn Profile](https://www.linkedin.com/in/philiprehberger)

License
-------

[](#license)

[MIT](LICENSE)

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance84

Actively maintained with recent releases

Popularity10

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 85.2% 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

5

Last Release

141d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/cfd7d24cbbf32400fa13ce0bbe7a31edd2d66a6d4488eafdb3d64c5337bf0435?d=identicon)[philiprehberger](/maintainers/philiprehberger)

---

Top Contributors

[![philiprehberger](https://avatars.githubusercontent.com/u/8218077?v=4)](https://github.com/philiprehberger "philiprehberger (23 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (4 commits)")

---

Tags

urlsluglaraveleloquentseo

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/philiprehberger-laravel-slug-generator/health.svg)

```
[![Health](https://phpackages.com/badges/philiprehberger-laravel-slug-generator/health.svg)](https://phpackages.com/packages/philiprehberger-laravel-slug-generator)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3345.4M354](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58190.1k21](/packages/api-platform-laravel)[laravel/cashier

Laravel Cashier provides an expressive, fluent interface to Stripe's subscription billing services.

2.6k31.8M158](/packages/laravel-cashier)[laravel/scout

Laravel Scout provides a driver based solution to searching your Eloquent models.

1.7k57.2M676](/packages/laravel-scout)[pressbooks/pressbooks

Pressbooks is an open source book publishing tool built on a WordPress multisite platform. Pressbooks outputs books in multiple formats, including PDF, EPUB, web, and a variety of XML flavours, using a theming/templating system, driven by CSS.

45844.8k1](/packages/pressbooks-pressbooks)[simplestats-io/laravel-client

Server-side analytics for Laravel that follows the full funnel from visit to registration to payment, attributed to the channel that drove it. Revenue, MRR, churn and ad-spend profit (ROAS/CAC) per channel. GDPR compliant, ad-blocker proof.

5226.7k](/packages/simplestats-io-laravel-client)

PHPackages © 2026

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