Skip to main content
Back to packages
1,545 GitHub stars

spatie/laravel-sluggable

View on GitHub

Description

Generate slugs when saving Eloquent models

This package generates a unique slug for any Eloquent model whenever it is created or updated. Add a #[Sluggable] attribute to the model and the package handles the rest.

use Spatie\Sluggable\Attributes\Sluggable;
 
#[Sluggable(from: 'title', to: 'slug')]
class Post extends Model
{
}
 
$post = Post::create(['title' => 'activerecord is awesome']);
$post->slug; // "activerecord-is-awesome"

For features that need closures (custom source callables, scoped uniqueness, conditional skip, custom suffix generators) use the HasSlug trait with a getSlugOptions() method instead.

Highlights

  • Unique slugs out of the box, with a configurable -1, -2, ... suffix on collisions.
  • Self-healing URLs: route keys that combine the slug with the primary key (hello-world-5) so renaming a model never breaks an existing link. Stale slugs return a 308 redirect to the canonical URL.
  • Translatable slugs through HasTranslatableSlug and spatie/laravel-translatable.
  • Overridable actions: swap the slug generator or the self-healing URL logic for your own class via a config file.
  • Laravel Boost skill bundled with the package, so AI assistants know how to scaffold sluggable models in your project. Boost discovers it automatically once both packages are installed.

Self-healing URLs combine the slug with the primary key. The HasSlug trait is required alongside the attribute, because it overrides Eloquent's route key and route binding methods.

#[Sluggable(from: 'title', to: 'slug', selfHealing: true)]
class Post extends Model
{
use HasSlug;
}
 
// /posts/hello-world-5 → 200
// /posts/old-title-5 → 308 to /posts/hello-world-5

Recent Courses on Laravel Daily

Laravel 13 Eloquent: Expert Level

41 lessons
1 h 34 min

Queues in Laravel 13

18 lessons
1 h 12 min read

How to Structure Laravel 13 Projects

16 lessons
1 h 32 min read

We'd Love Your Feedback

Tell us what you like or what we can improve

Feel free to share anything you like or dislike about this page or the platform in general.