slug()

Turn any text into a URL-friendly slug.

Syntax\Illuminate\Support\Str::slug($title, '-');

The Str::slug() method generates a URL-friendly "slug" from a string. It lowercases the text, removes accents and replaces spaces and symbols with a separator (a hyphen by default).

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • A blog engine generates a URL-safe slug from the post title when an author publishes a new article, storing it for canonical routing.
  • A multi-language site calls Str::slug() with a custom separator and locale to correctly handle accented characters in French and German titles.
  • A file-upload handler converts the original filename to a slug before storing it on disk, preventing directory traversal and special-character issues.

More examples

Basic slug from a post title

Converts a plain post title to a URL-safe slug by lowercasing, removing punctuation, and joining words with hyphens.

Example · php
use Illuminate\Support\Str;

$title = 'Hello World! Welcome to Laravel.';
$slug  = Str::slug($title);
// => 'hello-world-welcome-to-laravel'

Custom separator and language

Passes a custom separator and language hint to Str::slug() so accented characters are transliterated correctly.

Example · php
use Illuminate\Support\Str;

// Underscore separator
$slug = Str::slug('Mon Article en Francais', '_');
// => 'mon_article_en_francais'

// Accents stripped for non-ASCII
$slug2 = Str::slug(' Cafe au lait', '-', 'fr');
// => 'cafe-au-lait'

Unique slug generation in a model

Generates a base slug then appends an incrementing suffix until a unique slug that does not yet exist in the database is found.

Example · php
// In a model observer or service
public function uniqueSlug(string $title): string
{
    $base = Str::slug($title);
    $slug = $base;
    $i    = 1;

    while (Post::where('slug', $slug)->exists()) {
        $slug = $base . '-' . $i++;
    }

    return $slug;
}
// 'my-post', 'my-post-1', 'my-post-2', ...

Discussion

  • Be the first to comment on this lesson.