slugme.ioclean-url-slug-generator

How to Create URL Slugs in PHP and Laravel

Generate clean URL slugs in PHP with Laravel's Str::slug, cocur/slugify, Symfony's AsciiSlugger or plain PHP, plus unique slugs in Eloquent. All examples tested.

By 4 min read
How to Create URL Slugs in PHP and Laravel

PHP has excellent slug tooling — Laravel ships one, Symfony ships one, and the most popular standalone library has been around for a decade. They differ in the details that matter: case, German umlauts, apostrophes and what happens to non-Latin scripts. This guide covers each one with output tested on PHP 8.4 (illuminate/support 13, cocur/slugify 4.7, symfony/string 8.1).

Need slugs right now, without code? Use the URL slug generator, or paste a whole column of titles into the bulk slug generator and download a CSV.

Laravel: Str::slug

Str::slug is available in every Laravel app:

use Illuminate\Support\Str;

Str::slug('Laravel 5 Framework');        // 'laravel-5-framework'
Str::slug('Laravel 5 Framework', '_');   // 'laravel_5_framework'
Str::slug('Straße & Café');              // 'strasse-cafe'
Str::slug("Don't Stop");                 // 'dont-stop'
Str::slug('Привет мир');                 // 'privet-mir'

Its full signature is Str::slug($title, $separator = '-', $language = 'en', $dictionary = ['@' => 'at']). The language argument controls transliteration, which matters for German:

Str::slug('Größe Über');                 // 'grosse-uber'
Str::slug('Größe Über', '-', 'de');      // 'groesse-ueber'

And the dictionary converts characters to words before slugging. By default @ becomes at, so hello@example.com turns into hello-at-examplecom. Pass your own array to add '&' => 'and' or remove the @ rule.

One limitation: scripts without a Latin transliteration in Laravel's tables — Chinese, for example — return an empty string. Always add a fallback (see the model example below).

cocur/slugify

cocur/slugify is the standard choice outside Laravel, with bridges for Symfony, Twig and others:

composer require cocur/slugify
use Cocur\Slugify\Slugify;

$slugify = new Slugify();
$slugify->slugify('Hello World!');        // 'hello-world'
$slugify->slugify('Hello World', '_');    // 'hello_world'
$slugify->slugify('Größe Über');          // 'groesse-ueber'
$slugify->slugify('Łódź Guide');          // 'lodz-guide'

Its defaults already write German umlauts as ae/oe/ue. One trap we hit while testing: passing a rulesets array to the constructor replaces the default rules instead of adding to them. new Slugify(['rulesets' => ['default', 'german']]) returned an empty slug for Cyrillic and od-guide for "Łódź Guide". To add a language, activate it on a default instance instead:

$slugify = new Slugify();
$slugify->activateRuleSet('german');       // keeps all the other rules

Symfony: AsciiSlugger

Symfony's String component includes a slugger that uses the intl extension for transliteration:

use Symfony\Component\String\Slugger\AsciiSlugger;

$slugger = new AsciiSlugger();
$slugger->slug('Wôrķšƥáçè ~~sèťtïñğš~~')->lower();   // 'workspace-settings'
$slugger->slug('Straße & Café');                     // 'Strasse-Cafe'  ← keeps case!

$german = new AsciiSlugger('de');
$german->slug('Größe Über')->lower();                // 'groesse-ueber'

Two things to remember: AsciiSlugger keeps the original case, so always chain ->lower(), and it returns a UnicodeString object, so cast with (string) when you need a plain string. With intl installed it also transliterates Chinese to pinyin (影師嗎 → ying-shi-ma), which Laravel and cocur do not.

Plain PHP: a dependency-free slugify

If you can't add packages but have the intl extension (most hosts do), PHP's ICU transliterator does the heavy lifting:

function slugify(string $text, string $separator = '-'): string
{
    $text = str_replace('&', ' and ', $text);
    $text = preg_replace("/['’]/u", '', $text);          // don't -> dont
    $text = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $text);
    $text = preg_replace('/[^a-z0-9]+/', $separator, $text);
    return trim($text, $separator);
}

slugify('Straße & Café');           // 'strasse-and-cafe'
slugify("Don't Stop Me Now");       // 'dont-stop-me-now'
slugify('Łódź — Guide (2026)!');    // 'lodz-guide-2026'
slugify('Привет мир');              // 'privet-mir'
slugify('Hello World', '_');        // 'hello_world'

Any-Latin converts other scripts to Latin letters, Latin-ASCII flattens accents and special letters like ß and Ł, and Lower() lowercases — all in one ICU call. Avoid the older iconv('UTF-8', 'ASCII//TRANSLIT', …) approach: its output depends on the server's locale settings and can differ between your laptop and production.

To cap the length without cutting a word in half:

function limitSlug(string $slug, int $max, string $separator = '-'): string
{
    if (strlen($slug) <= $max) {
        return $slug;
    }
    $cut = substr($slug, 0, $max + 1);
    return str_contains($cut, $separator)
        ? substr($cut, 0, strrpos($cut, $separator))
        : substr($slug, 0, $max);
}

limitSlug(Str::slug('The Ultimate Guide to On-Page SEO for Beginners'), 30);
// 'the-ultimate-guide-to-on-page'

Unique slugs in Laravel Eloquent

The slug usually lives in a database column and must be unique. Generate it once, when the model is created:

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Post extends Model
{
    protected static function booted(): void
    {
        static::creating(function (Post $post) {
            $post->slug ??= static::uniqueSlug($post->title);
        });
    }

    public static function uniqueSlug(string $title): string
    {
        $base = limitSlug(Str::slug($title), 70) ?: 'post';
        $slug = $base;
        $n = 2;

        while (static::where('slug', $slug)->exists()) {
            $slug = "{$base}-{$n}";
            $n++;
        }

        return $slug;
    }
}

And in the migration, back it with a unique index:

$table->string('slug', 80)->unique();

Why both? The while loop handles the normal case, but two requests creating "My Post" at the same moment can both see the slug as free. The unique index makes the database the final judge, so one insert fails instead of silently creating a duplicate URL. Catch Illuminate\Database\UniqueConstraintViolationException and retry if that matters for your app. We cover the trade-offs — counters, IDs, scoping — in how to handle duplicate slugs.

Notice what the model does not do: it doesn't regenerate the slug in an updating hook. Titles get edited all the time; URLs should not. If you deliberately change a slug, keep the old one and redirect it.

Finally, use the slug for route model binding:

// routes/web.php
Route::get('/blog/{post:slug}', [PostController::class, 'show']);

Which should you use?

Situation Use
Laravel app Str::slug($title, '-', $locale)
Symfony app AsciiSlugger with ->lower()
Any other PHP project cocur/slugify
No Composer packages, intl available The transliterator_transliterate() function above
Need Chinese → pinyin Symfony AsciiSlugger or the intl function

See how these compare to JavaScript, Python and Ruby libraries on the same inputs in slugify libraries compared.

Frequently asked questions

How do I make a slug unique in Laravel?

Check for an existing slug in the creating model event and append -2, -3… until it is free, and keep a unique index on the slug column so concurrent requests can't both win. Packages such as spatie/laravel-sluggable automate this.

Should the slug change when the title is updated?

No. A slug is part of a public URL; regenerating it on every title edit breaks links. Generate it only on create, and if you deliberately change it later, store the old slug and 301-redirect it.

Why does Str::slug return an empty string?

Str::slug transliterates to ASCII and removes anything it can't convert. Chinese titles, for example, come back empty. Use Symfony's AsciiSlugger (which transliterates to pinyin with the intl extension) or add a fallback such as the record ID.

Keep reading